I am new here and I would greatly appreciate some help with a problem that I have been struggling with all day.
Consider these 2 tables:
albums (pkey: id) years (pkey: album_id, year)
id genre_id album_id year
--- -------- -------- ----
450 1 450 2000
451 1 450 2001
452 1 450 2002
453 2 451 2005
454 3 451 2012
452 1998
It may seem strange, but please assume that a single album can be associated with multiple years.
I want to select all albums in genre 1, sorted by the latest year of each of those albums. (Assume is is possible to sort by year).
So, I want this result:
id year
----- ----
451 2012
450 2002
452 1998
This is where I am at…
Obviously, I need to join the tables before ordering the results:
SELECT id, year
FROM albums INNER JOIN years ON albums.id = years.album_id
WHERE genre_id = 1
ORDER BY year;
This selects every year record for each album in genre 1, instead of only the latest year record for each album in genre 1.
Somehow, I need to incorporate a sub query, like this, to limit the years joined to the album table, to only the latest year for that album, and then sort again:
SELECT year FROM years WHERE album_id = ??? ORDER BY year DESC LIMIT 1;
1 Answer