我有一个包含3个表的MYSQL Db:
我的目标是显示所有艺术家的列表,并列出每个艺术家的名字旁边,这个艺术家发布的所有专辑的标题。 (专辑“仅属于”一位艺术家,艺术家当然可能拥有多张专辑)
如果可以获得如下结果,那就太好了。
1“ac / dc”3“让摇滚乐”
1“交流/直流”4“高压”
2“深紫色”45“机头”
2“深紫色”49“在岩石中”
3“motorhead”666“黑桃王牌”num
(每行中的第一个数字是artist_id,第二个是album_id)。
对此有什么合适的查询?
答案 0 :(得分:1)
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
而且,只是为了好玩,如果有艺术家尚未发布任何专辑,那该怎么办呢?
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
答案 1 :(得分:1)
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
答案 2 :(得分:0)
这样的事情:
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
答案 3 :(得分:0)
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