MySQL (or PHP?) group results by fields data [duplicate]
Possible Duplicate:
MySQL (or PHP?) group results by field data
Guys, I have a database (mysql) similar to this now:
ID meta_key meta_value name
1 _group 1 John
2 _group 1 Andrea
3 _group 1 Jack
4 _group 2 Mike
5 _group 2 Kurt
6 _group 3 Alice
and I need to sort / display it like this:
group name
-----------------------
1 John
Andrea
Jack
-----------------------
开发者_运维技巧 2 Mike
Kurt
-----------------------
3 Alice
-----------------------
I had a similar issue before, thanks for the previus help! But now i'm stucked with this.
I really appreciate your help.
The display portion you could do with PHP:
$display = "Group\tName";
$old_group = "";
while ($row = mysql_fetch_assoc($result)) {
if ($row['meta_value'] != $old_group) {
$old_group = $row['meta_value'];
$display .= "----------------------------\n" . $row['group'];
}
$display .= "\t" . $row['name'] . "\n";
}
echo "<pre>" . $display . "</pre>";
Untested, but pending any minor errors should display it how you want.
If you mean whether to group in your mysql query or later using PHP? Then do with Mysql, that would remove your headache to write PHP code to group and sort again. In case, you need to add more sortable columns later, mysql sorting will very easily do that whereas more logic may be needed for doing with PHP
精彩评论