Mysql

對行值有 LIMIT 的 mySQL 查詢

  • September 30, 2021

我正在嘗試用一個查詢替換很多這樣的查詢。

SELECT * FROM y WHERE x = a ORDER BY timestamp LIMIT 50
SELECT * FROM y WHERE x = b ORDER by timestamp LIMIT 50
SELECT * FROM y WHERE x = c ORDER by timestamp LIMIT 50
SELECT * FROM y WHERE x = d ORDER by timestamp LIMIT 50
SELECT * FROM y WHERE x = .....
  • 這是為了顯示一個看板樣式的列板,每列有 50 個有序結果
  • SELET * FROM y ORDER by timestamp 將返回 100k 到 1M 行,因此太慢而無法限制程式碼。
  • 我想獲得每個 X 值的前 50 個結果(可能有 100 個 X 值,因此目前有 100 個查詢)
  • 順序很重要
  • 我不清楚 GROUP BY 可以在這裡提供幫助。

對於合理的 MySQL 新版本,您可以使用視窗函式:

SELECT *
FROM (
   SELECT y.*, ROW_NUMBER() OVER (PARTITION BY x ORDER BY ts) as rn 
   FROM y
   WHERE x IN (a,b,c,d)
) AS t
WHERE rn <= 50
ORDER BY ts

引用自:https://dba.stackexchange.com/questions/300411