我有一個我無法弄清楚的 MySQL 問題。
我運行一個查詢:
SELECT id, totalsum FROM table ORDER BY totalsum DESC
這可能會給我以下結果:
1, 10000
4, 90000
8, 80000
3, 50000
5, 40000
需要的是一個應該像這樣作業的代碼:
SELECT id, totalsum
FROM table ORDER BY totalsum DESC
START LISTING FROM id=8 AND CONTINUE TO THE END OF RESULT / LIMIT
結果像這樣
8, 80000
3, 50000
5, 40000
我不能使用這個查詢:
SELECT id, totalsum
FROM table
WHERE id>=8
ORDER BY totalsum DESC
因為 id 可以同時是 < 和 >。
已嘗試使用 LIMIT AND OFFSET 但速度非常慢。
任何指向我正確方向的建議將不勝感激!
uj5u.com熱心網友回復:
這是一種方法:
- 根據總和降序為每一行分配一個 row_num (CTE)
- 從上面選擇where row_num >= the row_num of id=8
create table a_table (
id int,
total int);
insert into a_table values
(1, 100000),
(4, 90000),
(8, 80000),
(3, 50000),
(5, 40000);
with cte as (
select id,
total,
row_number() over (order by total desc) as row_num
from a_table)
select *
from cte
where row_num >= (select row_num from cte where id=8);
結果:
id|total|row_num|
-- ----- -------
8|80000| 3|
3|50000| 4|
5|40000| 5|
編輯:如果其他行的總計相同,上述查詢可能會回傳錯誤的結果。有評論說的不錯,直接用下面的查詢就可以了:
select id, total
from a_table
where total <= (select total from a_table where id=8)
order by total desc;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/535379.html
標籤:数据库选择
上一篇:在VUE.js中顯示JSON
