Not sure if the title really defines what I'm looking for.
What I want to do is return all rows that have a matching column value. Display the first value only once, and display all other columns. Here's a visual of the table:
id name data
======================
0 john data1
1 john data2
2 jane data1
3 jane data2
4 jane data3
So the result would be displayed as:
john
data1
data2
jane
data1
data2
data3
I know I can use DISTINCT to get the name once, but would I need to get all names from a query first, then do a loop and run a second query, or can I do this in one statement?
Right now I have a foreach that uses an array to loop through and get everything. So it currently displays as:
john - data1
john - data2
jane - data1
jane - data2
jane - data3
It just seems aesthetically bad to show the first column every time, but I'm not too sure how to go about this efficiently.
Thank you for any help.
解决方案
You can do this without the use of a PHP function by taking advantage of MySQL's group_concat function which does exactly what you're looking for:
SELECT name, group_concat(`data`) FROM table GROUP BY name;
Will return one column with "John" and a second column with "data1,data2". You can then use PHP's explode() function on the second column to get an array containing "data1" and "data2".