[英]How to find the shortest song name in each music album
我使用 mysql 并且我有两个具有多对多关系的表,第三个表包含它们的外键:
album table:
id name
composition table:
id name duration
links table:
id album_id composition_id
如何创建 sql 查询以按时长获取每张专辑中最短的歌曲名称? 我试图让一些想法像:
SELECT al.name, c.name FROM album al
JOIN links l ON l.album_id = al.id
JOIN composition c ON l.composition_id = c.id
GROUP BY al.name
HAVING //don't know what next
如果您使用 PostgreSQL:
SELECT DISTINCT ON (al.name) al.name, c.name FROM album al
JOIN links l ON l.album_id = al.id
JOIN composition c ON l.composition_id = c.id
ORDER BY al.name, c.duration
SELECT album_name, composition_name, duration
FROM (
SELECT al.name AS album_name,
c.name AS composition_name,
c.duration
ROW_NUMBER() OVER (PARTITION BY al.id ORDER BY c.duration) AS rownum
FROM album al
JOIN links l ON l.album_id = al.id
JOIN composition c ON l.composition_id = c.id
) AS t
WHERE rownum = 1;
Window 功能需要 MySQL 8.0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.