Home  >  Article  >  Backend Development  >  mysql查询分组

mysql查询分组

WBOY
WBOYOriginal
2016-06-06 20:15:411542browse

数据表:
id n t
1 a 1
2 b 1
3 c 2
4 d 2
5 e 3
1 f 3


我想取出来的数据根据t分组这样:

<code class="php">  [
      1=>[
          0=>[
              'id'=>1,
              'n'=>'a',
              't'=>1
          ],
          1=>[
              'id'=>2,
              'n'=>'a',
              't'=>1
          ]
      ] 
  ]</code>

我用group by后,每个分类只会得到一个数据,而不是全部

回复内容:

数据表:
id n t
1 a 1
2 b 1
3 c 2
4 d 2
5 e 3
1 f 3


我想取出来的数据根据t分组这样:

<code class="php">  [
      1=>[
          0=>[
              'id'=>1,
              'n'=>'a',
              't'=>1
          ],
          1=>[
              'id'=>2,
              'n'=>'a',
              't'=>1
          ]
      ] 
  ]</code>

我用group by后,每个分类只会得到一个数据,而不是全部

group by就是只返回第一条数据的。如果要返回分组中的字段信息可以用下面的sql

<code>select id,user_id,GROUP_CONCAT(`order_no`) ,count(`id`) from `table` group by `user_id`</code>

GROUP_CONCAT这个可以将需要全部列出来的值查询出来,并放在一个字段中,以逗号隔开。

你可以用Order by,然后在php中遍历分组
另一种方式就是group_concat + concat了,比如
select t, concat('[', group_concat(concat('{id:',id,',n:"', n, '"}')), ']') as details from table group by t
这样应该是得到类似
1 [{id:1,n:"a"},{id:2,n:"a"}] 这种记录,你再json_decode就行了

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn