通过关系表间接连接2个表

时间:2011-01-21 04:31:44

标签: php sql mysql

我正在尝试通过关系表获取与乐队相关的流派。有没有办法利用JOIN通过band_genre表连接类型表?显然,使用多个查询很容易实现,但我想知道这种查询有多优雅。

谢谢:)

# (Bands) Table

band_id = 1
band_name = The Roots

# (Genres) Table

genre_id = 1
genre_type = Hip-hop

genre_id = 2
genre_type = Soul

# (Band_Genre) Table

bg_id = 1
bg_band = 1
bg_genre = 1

bg_id = 2
bg_band = 1
bg_genre = 2

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT * FROM Bands b
INNER JOIN Band_Genre bg ON b.band_id = bg.bg_band
INNER JOIN Genres g ON bg.bg_genre = g.genre_id

答案 1 :(得分:1)

我认为这是你想要的那种查询......

SELECT `band_name`, `genre_type`
FROM `bands`
INNER JOIN `band_genre` ON `band_id` = `bg_band`
INNER JOIN `genres` ON `genre_id` = `bg_genre`

......但我不确定你对JSON的看法。所以这可能不适合你。