可能重复:
Mysql single query join 3 table and get all the results我想要得到的所有结果使用单查询加盟3台
嗨,我想列出所有歌曲的专辑,我想列出所有例如,单个歌曲的艺术家见下面。
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
我的表是歌曲,专辑,艺术家,song_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_is |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中的所有结果?
非常感谢您的帮助。
James。
好吧现在我得到了我想要的结果,感谢每一个。
$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";
你怎么知道哪些歌曲在哪个专辑? –
我正在使用$ _GET ['id'];方法来获取相册ID从url – James
这是您以前的帖子的确切副本:http:// stackoverflow。com/questions/6682386/mysql-single-query-join-3-table-and-get-all-the-results – jworrin