tags:

views:

43

answers:

2

What I'm trying to do is I have my tables structured like so:

The Monkees - I'm A Believer
The Monkees - Daydream Believer  
The Beatles - Hello, Goodbye
The Beatles - Yellow Submarine 

With the artist and title names in the same row and I'm trying to display them like this in the search results:

The Monkees:
I'm A Believer
Daydream Believer

The Beatles:
Hello, Goodbye
Yellow, Submarine

With artist names only appearing once, like a category above the song titles.

Is there any way I can achieve this structure with MySQL statements?

EDIT:

I've tried using group_concat, but I can only get song titles to show up, and not artist names. My code:

<?php
include 'config.php';
$trimmed = $_GET['term'];

$res = mysql_query("SELECT DISTINCT artist, GROUP_CONCAT(title SEPARATOR ', ') AS artists FROM songs WHERE artist LIKE '%$trimmed%'");
$row = mysql_fetch_array($res, MYSQL_ASSOC);
$result = $row['artists'];

echo $result;

?>
A: 

Assuming a table called tracks with columns artist and track I think this would be close.

SELECT CONCAT(artist, ':\n', group_concat(track  separator '\n')) AS ArtistAndTracks
FROM 
tracks
GROUP BY atist

Edit: I just noticed this is for PHP - Johnathan's answer is probably more appropriate.

Martin Smith
+1  A: 

Have you looked at doing a group_concat? Other than that, you can create an array as you loop through doing something like:

$music = array();
$result = mysql_query("SELECT ARTIST,ALBUM FROM MUSIC") or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
    $music[$row['ARTIST']][] = $row['ALBUM'];
}
echo '<pre>'.print_r($music,1).'</pre>';
Jonathan Kuhn
After doing some research on group_concat I've gotten stuck, I can currently only get song titles to display. I've posted my code in my original post. I've used your php code and it works wonderfully, though after looking for a solution, I still have no idea how to format artist names and songs titles to echo appropiately from an array with links, css, etc. I'm still very much learning php and mysql as you can tell. I'm going to do some more research and see if I can find these answers myself, though I would greatly appreciate it if anybody would help me out! :)
Nevermind about that, I just found out about working with nested loops and such and so have figured out how to format with arrays. I'm sure after some more googling I'll figure out how to work with group_concat.Thanks for your help!