Question

I have a MYSQL Db with 3 tables:

  1. artists(artist_id,name)
  2. albums (album_i,title) and a third correlation table:
  3. albums_artists (album_id, artist_id)

My goal is to display a list of all the artists and next to each artist's name, the titles of all the albums this artist released. (An album "belongs" to only one artist, an artist may have more than one album of course)

It would be great if a could get a result like:

1 "ac/dc" 3 "let there be rock"
1 "ac/dc" 4 "high voltage"
2 "deep purple" 45 "machine head"
2 "deep purple" 49 "in rock"
3 "motorhead" 666 "the ace of spades" num

(The first number in each row being the artist_id, and the second the album_id).

What would be the appropriate query for that?

Was it helpful?

Solution

select
  artist_id,
  album_id,
  ...
from
  albums_artists
join albums on albums.id = albums_artists.album_id
join artists on artists.id = albums_artists.artist_id

OTHER TIPS

SELECT ar.artist_id, ar.name, al.album_id, al.title
    FROM artists ar
        INNER JOIN albums_artists aa
            ON ar.artist_id = aa.artist_id
        INNER JOIN albums al
            ON aa.album_id = al.album_id
    ORDER BY ar.name, al.title

And, just for fun, what if there's an artist who hasn't released any albums yet.

SELECT ar.artist_id, ar.name, al.album_id, al.title
    FROM artists ar
        LEFT JOIN albums_artists aa
            INNER JOIN albums al
                ON aa.album_id = al.album_id
            ON ar.artist_id = aa.artist_id
    ORDER BY ar.name, al.title
select a.artist_id, a.name, al.album_id, al.title
from artists a, albums al, albums_artists ala
where a.artist_id = ala.artist_id
and ala.album_id = al.album_id
order by ala.artist_id

Something like this:

select ar.artist_id, ar.name, al.album_id, al.title
  from artists ar
  join album_artists aa on aa.artist_id = ar.artist_id
  join albums al on al.album_id = aa.album_id and ar.artist_id = aa.artist_id
order by ar.artist_id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top