[英]SQL Window Functions - SELECT DISTINCT ORDER BY LIMIT
我在PostgreSQL數據庫中有這3個表:
基本上每個藝術家都有多個專輯,每個專輯都有多首歌曲。
我的查詢正確地返回了25個不同的artist.id,其中一首歌的標題以“The”開頭,以相冊的年份排序:
SELECT id
FROM (
-- Remove the duplicate artists
SELECT DISTINCT ON (a.id) id, row
FROM (
-- Get all matching artists
-- This is slow because there is no limit
SELECT
artist.id,
row_number() OVER(ORDER BY album.year DESC) as row
FROM artist
LEFT JOIN album ON album.artist_id = artist.id
LEFT JOIN song ON song.album_id = album.id
WHERE song.title ilike 'The %'
ORDER BY album.year DESC
) as a
) as b
ORDER BY row
LIMIT 25
然而,它是緩慢且低效的,因為最里面的查詢沒有LIMIT,所以它將在整個表中搜索所有可能的匹配。 理想情況下,當找到25個不同的artist.id時,它會停止搜索。
可以重寫或優化此查詢以更快地執行嗎?
謝謝!
select id, year
from (
SELECT DISTINCT ON (artist.id) artist.id, album.year
FROM artist
inner JOIN album ON album.artist_id = artist.id
inner JOIN song ON song.album_id = album.id
WHERE song.title ilike 'The %'
ORDER BY artist.id, album.year DESC
) s
order by year desc
LIMIT 25
當ilike表達式以%
開頭時, song.title
上的索引可以提供幫助
試試這個,應該比你當前的查詢更快
SELECT
artist.id,
MAX( album.year ) as latest_album_date
FROM
artist
JOIN album ON album.artist_id = artist.id -- JOIN, not LEFT JOIN
JOIN song ON song.album_id = album.id -- Since you have song.title in WHERE clause, it makes no sense to make these as a LEFT JOIN
WHERE
song.title ilike 'The %'
GROUP BY
artist.id
ORDER BY
latest_album_date DESC
limit 25;
試試這個,
Select id, year
from (
SELECT DISTINCT ON (artist.id) artist.id, album.year
FROM artist
rightJOIN album ON album.artist_id = artist.id
left JOIN song ON song.album_id = album.id
WHERE song.title ilike 'The %'
ORDER BY artist.id, album.year DESC
) s
order by year desc
LIMIT 25
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.