Using PHP and MySQL I designed a database for a music website:
Artists (artist_id, artist_name);
Tracks (track_id, track_name);
ArtistTracks (track_id, artist_id)
That is good when there is no more than one row for any combination. But there could be a duet--two artists having the same track.
I added a duet and to get the latest tracks I did:
SELECT Tracks.track_id, Tracks.track_name, Artists.artist_name
FROM ArtistTracks, Tracks, Artists
WHERE ArtistTracks.track_id = Tracks.track_id
AND ArtistTracks.artist_id = Artists.artist_id
ORDER BY tracks.track_id DESC LIMIT 10';
and fair enough the result is:
Array
(
[0] => Array
(
[track_id] => 33
[track_name] => track duet.
[artist_name] => artist b
)
[1] => Array
(
[track_id] => 33
[track_name] => track duet.
[artist_name] => artist b
)
What is wrong with this design?
How do I select/display duets?
Do I need to loop over the whole array and check if a track_id matches another track_id?
I made the tracks appear as they should for two artists sharing a track_name.
A problem is that I had 6 templates for my whole website and now I have 12 because there are too many conditionals.
A problem is that I need to update any change in the site twice, because of the conditionals for displaying the duets.
Should I make another table for duets?
First determine the side which has higher importance - probably artists. It might be the other way round in another page.
Your query makes little sense: you're completely missing the JOIN construct. Get your artists and join their songs. You may either use grouping and concatenate all songs for one artist into one field by using GROUP_CONCAT or not group the results and process the set with PHP. (For every track it returns a row with artist name and track name.)
Grouping by artist:
SELECT a.artist_name, GROUP_CONCAT(a.track_name SEPARATOR '; ') AS 'tracks' FROM artists a
LEFT JOIN ArtistsTracks at ON at.artist_id = a.artist_id
LEFT JOIN Tracks t ON at.track_id = t.track_id
GROUP BY a.artist_id
Grouping by track:
SELECT a.track_name, GROUP_CONCAT(a.artist_name SEPARATOR '; ') AS 'artists' FROM artists a
LEFT JOIN ArtistsTracks at ON at.artist_id = a.artist_id
LEFT JOIN Tracks t ON at.track_id = t.track_id
GROUP BY a.track_id
Plain result:
SELECT a.artist_name, a.track_name FROM artists a
LEFT JOIN ArtistsTracks at ON at.artist_id = a.artist_id
LEFT JOIN Tracks t ON at.track_id = t.track_id
Although the first two solutions run generally slower for large data-sets, you must account for the extra processing needed to be done by PHP for the last solution. If for example you want to link each track to its own page, you'd be better off with the last one.