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

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

Patricia Arquette
發布: 2024-11-15 14:41:03
原創
553 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板