加入多个表并显示从 id 链接的所有名称

Joining multiple tables and display all names linked from id

我已经使用我学到的正常形式重建了我的数据库,但现在我无法将它们与所有 table 重新组合成一个。

我有一个歌曲数据库,table的连接是这样链接的:

songs          artists            song_vocals         song_composers
--------------------------------------------------------------------
song_id        artist_id          song_id             song_id
title          artist_name        artist_id           artist_id

有多个 table 的外键指向艺术家 table。

而且我想显示名称为这样的所有信息,我不想按 id 显示它们:

song_id        title         vocal          composer
--------------------------------------------------------
1              ABC           John           Cat

到目前为止,我能做的最好的就是加入 3 个 tables,这只会给我 song_idtitle声乐:

SELECT songs.song_id, songs.title, artists.artist_name as vocal FROM songs
LEFT JOIN song_vocals ON
song_vocals.song_id = songs.song_id
left join artists ON
song_vocals.artist_id = artists.artist_id

如何加入更多?

您可以为作曲家创建一个 table 如果您还没有这样做,并在您的 song_vocals table 中添加外键,从您的声明中它是您的主要 table 无论如何。然后,您可以在艺术家之后向作曲家 table 添加另一个左连接,但不要忘记将 composers.composer_name (我假设)也放在您的 select 语句中。

表 song_vocals 和 song_composer

有什么区别
SELECT 
songs.title as SongTitle,
a1.artist_name as Vocal,
a2.artist_name as Composer
FROM songs
left join song_vocals ON song_vocals.song_id = songs.song_id
left join artists a1 ON song_vocals.artist_id = a1.artist_id
left join song_composers on songs.song_id = song_composers.song_id
left join artists a2  on a2.artist_id = song_composers.artist_id

这是您应该使用的代码块。 如果您有两个或更多指向 table 的链接,如果您使用 ALIAS,则可以多次使用 table。 在你的前任。 "a1","a2" 是您的别名