php按mysql字段分组取值,MySQL(或PHP?)按字段数据分组结果

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

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

-----------------------

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

(I'm working with to tables)

And I need to achieve:

group title coef

---------------------------------

1 Title 1 6

Title 2 2

Title 3 12

--------------------------------

2 Title 4 2

Title 5 3

--------------------------------

3 Title 6 7

--------------------------------

¿Is this even possible?

解决方案

This would my solution, althoug is not elegant at all

$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

");

?>

GroupName

<?php while($row = $result->fetch_assoc()){

$names = split(",",$row["names"]);

?>

<?php echo $row["group"] ?> <?php echo $names[0]; array_shift($names) ?><?php echo $name ?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值