MySQL(或 PHP?)按字段数据对结果进行分组 [英] MySQL (or PHP?) group results by field data
问题描述
我有一个与此类似的 MySQL 数据库:
I have a MySQL database that looks similar to this:
ID Group Name
1 1 John
2 1 Andrea
3 1 Jack
4 2 Mike
5 2 Kurt
6 3 Alice
我需要在如下所示的 html 表格中对结果进行排序:
I need to sort the results in a html table that looks like this:
Group Name
-----------------------
1 John
Andrea
Jack
-----------------------
2 Mike
Kurt
-----------------------
3 Alice
-----------------------
我不知道这应该用 SQL 查询(concat_group 或类似的东西)还是用 PHP 来完成,有人可以帮我吗?
I don't know if this should be done with a SQL query (concat_group, or something similar) or with PHP, can somebody please help me out?
伙计们,感谢下面的帮助,但我也需要完成类似的事情,就像这样:
Guys, thanks for the help below, but I also need to accomplish something similar, like this:
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 the same as the example above, something like this:
group name
-----------------------
1 John
Andrea
Jack
-----------------------
2 Mike
Kurt
-----------------------
3 Alice
-----------------------
现在我的问题有了新的维度.我的数据库看起来像:
Now my problem has taken new dimensions. My database looks like:
b.ID b.meta_key b.meta_value a.title
1 group 1 Title 1
2 group 1 Title 2
3 group 1 Title 3
4 group 2 Title 4
5 group 2 Title 5
6 group 3 Title 6
7 coef 6 Title 1
8 coef 4 Title 2
9 coef 12 Title 3
9 coef 2 Title 4
9 coef 3 Title 5
9 coef 7 Title 6
(我正在处理表格)
我需要实现:
group title coef
---------------------------------
1 Title 1 6
Title 2 2
Title 3 12
--------------------------------
2 Title 4 2
Title 5 3
--------------------------------
3 Title 6 7
--------------------------------
¿这可能吗?
推荐答案
这就是我的解决方案,虽然一点也不优雅
This would my solution, althoug is not elegant at all
<?php
$dbc = new MySQLI(DBHOST,DBUSER,DBPASS,DB);
$result = $dbc->query("
SELECT
p.Group as 'group',
GROUP_CONCAT(name) as names
FROM prueba p
GROUP BY p.Group
");
?>
<table>
<tr>
<th>Group</th>
<th>Name</th>
</tr>
<?php while($row = $result->fetch_assoc()){
$names = split(",",$row["names"]);
?>
<tr>
<td><?php echo $row["group"] ?> </td>
<td><?php echo $names[0]; array_shift($names) ?></td>
</tr>
<?php foreach( $names as $name){ ?>
<tr>
<td></td>
<td><?php echo $name ?></td>
</tr>
<?php } ?>
<?php } ?>
</table>
这篇关于MySQL(或 PHP?)按字段数据对结果进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!