mysql查询第一列,mysql-返回第一列一次和所有对应的列数据

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".

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值