[英]How do i write a query to select the top and bottom 3 values from 2 tables using a single query?
關系數據庫包含2個表:書和作者,每個表包含一百萬行以上。
這些表被描述為:書籍(標題,已售副本),其中標題是主鍵作者(作者,標題),其中標題是指書籍
編寫一個SINGLE查詢,根據已售副本數顯示前3名作者和后3名作者。
我正在嘗試解決此問題,但是失敗了。
select *
from authors a
left join books b on a.authortitle = b.title
order by b.sold;
當我嘗試此操作時,這是我收到的回復。
select *
from authors a
left join books b on a.authortitle = b.title
order by b.sold
group by author;
錯誤1064(42000):您的SQL語法有錯誤; 檢查與您的MySQL服務器版本相對應的手冊,以在第1行的“按作者分組”附近使用正確的語法
我不確定這是什么意思。 有誰知道如何解決這個問題? 謝謝!
您可以使用UNION運算符。 像這樣的東西(此代碼未經測試:D)
(select * from authors a left join books b on a.authortitle = b.title order by b.sold limit 3)
union
(select * from authors aa left join books bb on aa.authortitle = bb.title order by bb.sold desc limit 3)
select a.*,
rank() over(partition by a.author order by b.copiessold asc) rk
from authors a
left join books b on a.authortitle = b.title
where rk<4
UNION ALL
select a.*,
rank() over(partition by a.author order by b.copiessold desc) rk
from authors a
left join books b on a.authortitle = b.title
where rk<4;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.