I use mysql and I have two tables with many to many relation and third table contains their foreign keys:
album table:
id name
composition table:
id name duration
links table:
id album_id composition_id
How can I create sql query to get the shortest song name in each album by duration? I tried to make somethink like:
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
CodePudding user response:
If you use 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
https://www.geekytidbits.com/postgres-distinct-on/
CodePudding user response:
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 functions require MySQL 8.0.