我有 6 張桌子:
相冊
id_album | title | id_band | year |
樂隊
id_band | name |style | origin
作曲家
id_musician | id_song
會員
id_musician | id_band | instrument
音樂家
id_musician | name | birth | death | gender
歌曲
id_song | title | duration | id_album
我需要撰寫一個查詢,在其中獲得成員較多的六個樂隊以及這些樂隊中最長的歌曲持續時間及其標題。
到目前為止,我可以獲得最大的樂隊:
SELECT bands.name, COUNT(id_musician) AS numberMusician
FROM bands
INNER JOIN members USING (id_band)
GROUP BY bands.name
ORDER BY numberMusician DESC
LIMIT 6;
我還可以獲得最長的歌曲:
SELECT MAX(duration), songs.title, id_album, id_band
FROM SONGs
INNER JOIN albums USING (id_album)
GROUP BY songs.title, id_album, id_band
ORDER BY MAX(duration) DESC
當我嘗試撰寫子查詢以獲取具有相應歌曲及其持續時間的樂隊時,就會出現問題。試圖用內部連接來做這件事也會給我帶來不想要的結果。有人可以幫助我嗎?
我試圖將子查詢放在哪里,但由于 MAX,我找不到如何做。
謝謝
uj5u.com熱心網友回復:
我發現使用橫向連接使查詢更容易撰寫。你已經有了很好的join邏輯,所以我們只需要將樂隊與音樂家的歌曲相關聯。
所以:
select b.name, m.*, s.*
from bands b
cross join lateral (
select count(*) as cnt_musicians
from members m
where m.id_band = b.id_band
) m
cross join lateral (
select s.title, s.duration
from songs s
inner join albums a using (id_album)
where a.id_band = b.id_band
order by s.duration desc limit 1
) s
order by m.cnt_musicians desc
limit 6
對于每個樂隊,子查詢m計算每個組的音樂家數量(其where子句與外部查詢相關),同時使用相關性和s檢索最長的歌曲。外部查詢只是結合資訊,然后orders選擇前6個波段。order bylimit
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/533108.html
