Mysql单个查询连接3表并获取所有结果

时间:2011-07-13 16:37:48

标签: php mysql

您好我想列出该专辑的所有歌曲,我想列出所有艺术家的个别歌曲,例如见下文。

1. Song Title 1
   - Artist 1, Artist 2, Artist 3    note:(all this individual artist have link to there artist page)
2. Song Title 2
   - Artist 1, Artist 2
3. Song Title 3
   - Artist 1, Artist 2, Artist 3

我的表格是歌曲,专辑,艺术家,歌曲_artist

歌曲表

+----+-----------+----------+
| id | song_name | album_id |
+----+-----------+----------+
| 1  | Title 1   | 2        |
| 2  | Title 2   | 2        |
| 3  | Title 3   | 2        |
+----+-----------+----------+

专辑表

+----+------------+
| id | album_name |
+----+------------+
| 1  | Album 1    |
| 2  | Album 2    |
| 3  | Album 3    |
+----+------------+

艺术家表

+----+-------------+
| id | artist_name |
+----+-------------+
| 1  | Artist 1    |
| 2  | Artist 2    |
| 3  | Artist 3    |
+----+-------------+

song_artist表

+--------+--------------+---------+
| id     | song_id      |artist_id|
+--------+--------------+---------+
| 1      | 1            | 1       |
| 2      | 1            | 5       |
| 3      | 1            | 3       |
| 4      | 2            | 3       |
| 5      | 2            | 1       |
| 6      | 3            | 2       |
| 7      | 3            | 1       |
+--------+--------------+---------+

这是我目前的代码。

$id =$_GET['id']; *// Get album id from url*
$query = "SELECT id, song_name, FROM song WHERE album_id = '".$id."'";
$result = mysql_query($query) or die("h".mysql_error());
while( $song = mysql_fetch_assoc($result)){
echo $song['song_name'];
$result1 = mysql_query("SELECT artist.artist_name as artist_name, artist.id as aid
FROM artist
INNER JOIN song_artist
ON artist.id = song_artist.artist_id
WHERE song_artist.song_id = '".$song['id']."' ");
while($row = mysql_fetch_array($result1)){
echo "<a href='".$row['sid']."'>".$row['artist_name']."</a>, ";
}
}

如何编写mysql单一查询以获取php中的所有结果?

提前感谢您的帮助。

詹姆斯。

好的我现在得到了我想要的结果,谢谢每一个人。

$query = "select s.id song_id, s.song_name, group_concat(art.artist_name) artname, a.id
        from song s 
        left outer join album a on a.id = s.album_id
        left outer join song_artist sa on sa.song_id = s.id
        left outer join artist art on art.id = sa.artist_id
        WHERE a.id= '".$id."'
        GROUP BY song_id";

3 个答案:

答案 0 :(得分:1)

SELECT s.song_name, a.artist_name, al.album_name
FROM artist a
LEFT JOIN song_artist sa ON sa.artist_id = a.id
LEFT JOIN song s ON s.id = sa.song_id
LEFT JOIN album al ON al.id = s.album_id

有关JOIN

的更多信息

答案 1 :(得分:1)

这可以获得专辑1的歌曲+艺术家。

SELECT song_name, group_concat(artist_name) 
FROM song 
LEFT JOIN song_artist ON song.id=song_artist.song_id 
LEFT JOIN artist ON song_artist.artist_id=artist.id 
WHERE song.album_id=1

请注意,您确实在另一个地方回答了这个问题。

答案 2 :(得分:0)

Select s.song_name ,art.artist_name,a.album_name from Song
join song_artist sa on sa.Song_id = s.Song_id
join Album a on a.album_id = s.Album_id
join Artist art on art.id = sa.artist_id