首頁 >資料庫 >mysql教程 >如何在 MySQL 中選擇前 N 個最大值:僅傳回 N 行或包含並列?

如何在 MySQL 中選擇前 N 個最大值:僅傳回 N 行或包含並列?

Patricia Arquette
Patricia Arquette原創
2024-11-15 14:41:03569瀏覽

How to Select the Top N Maximum Values in MySQL: Return Only N Rows or Include Ties?

MySQL: Selecting the Top N Maximum Values

Confusion often arises when attempting to retrieve the top N rows with the highest values in a specific column. The question is whether to return only the top N rows or include additional rows if they share the same maximum value.

To achieve the former, the following query will suffice:

SELECT *
FROM t
ORDER BY value DESC
LIMIT N

This query ensures that only the top N rows are returned, regardless of whether other rows have the same maximum value.

However, if the requirement is to include rows with equal maximum values, a more complex query is required:

SELECT *
FROM t
JOIN (
  SELECT MIN(value) AS cutoff
  FROM (
    SELECT value
    FROM t
    ORDER BY value
    LIMIT N
  ) tlim
) tlim
ON t.value >= tlim.cutoff;

Alternatively, the query can be simplified:

SELECT *
FROM t
JOIN (
  SELECT value
  FROM t
  ORDER BY value
  LIMIT N
) tlim
ON t.value = tlim.value;

Lastly, another method involves using the ANY function, but its compatibility with MySQL may vary:

SELECT *
FROM t
WHERE t.value >= ANY (
  SELECT value
  FROM t
  ORDER BY value
  LIMIT N
)

This approach also includes rows with the same maximum value, offering a conceptually clear solution to the problem.

以上是如何在 MySQL 中選擇前 N 個最大值:僅傳回 N 行或包含並列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn