Domanda

I've had a look at other examples and still can't figure out what would be the most efficient query to display results like this (Artist Name - Release Name - Year - YT) from these MySQL tables. I'll be using the ID's to link to separate pages too.

tbl_artists
artist_id       artist_name

tbl_releases
release_id      release_name    release_year    release_yt

tbl_release_artists
release_id      artist_id       artist_order

I previously had artist_id in tbl_releases but added a separate table (tbl_release_artists) and included it there as there is more than one artist on some releases/songs. How would I alter the query below to display all the artists that were on each release? I've read that the best solution is GROUP_CONCAT? Any help would be much appreciated. Thanks in advance.

SELECT Releases.artist_id, Releases.release_name, Releases.release_year, Releases.release_yt, Artists.artist_id, Artists.artist_name 
FROM tbl_releases AS Releases
LEFT JOIN tbl_artists AS Artists
USING ( artist_id )
ORDER BY Artists.artist_name, Releases.release_year, Releases.release_name ASC
È stato utile?

Soluzione

First, you need to fix the query to use the tbl_release_artists. I also added in table aliases to make the query more readable. These are abbreviations for table names, so repeated long names don't clutter up the query. Then you need to aggregate by each release using the group by clause:

SELECT r.release_name, r.release_year, r.release_yt, 
       group_concat(a.artist_id) as artist_ids,
       group_concat(a.artist_name) as artist_names
FROM tbl_release_artists ra join
     tbl_releases r
     on r.release_id = ra.release_id
     tbl_artists a
     on a.artist_id = ra.artist_id
GROUP BY r.release_year, r.release_name, r.release_yt
ORDER BY r.release_year, r.release_name ASC;

Of course, with multiple artists, ordering by the artist doesn't really make sense. So this just orders by release information.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top