Possible Duplicate:
Mysql single query join 3 table and get all the results
Hi i want to list all the song for the the album and i want to list all the artist for individual song see below for example.
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
My tables are song, album, artist, song_artist
song table
+----+-----------+----------+
| id | song_name | album_id |
+----+-----------+----------+
| 1 | Title 1 | 2 |
| 2 | Title 2 | 2 |
| 3 | Title 3 | 2 |
+----+-----------+----------+
album table
+----+------------+
| id | album_name |
+----+------------+
| 1 | Album 1 |
| 2 | Album 2 |
| 3 | Album 3 |
+----+------------+
artist table
+----+-------------+
| id | artist_name |
+----+-------------+
| 1 | Artist 1 |
| 2 | Artist 2 |
| 3 | Artist 3 |
+----+-------------+
song_artist table
+--------+--------------+---------+
| 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 |
+--------+--------------+---------+
This my current code.
$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>, ";
}
}
how do i write mysql single query to get all results in php?
Thank you for your help in advance.
James.
Ok Now i got the result what i want, thank for every one.
$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";
Using the query:
You’ll get results like:
And will have thus have to iterate over each song id to get the display information for each song from the results. Because you are doing it with one query, you’ll get duplicate song and album names when there are multiple artists for a song, but that’s the price you pay for conciseness.
UPDATE:
OR you can use GROUP_CONCAT on artist_name as Eljakim suggested if you won’t use artist information for anything except a concatenated display list.