Mysql query Group

Source: Internet
Author: User
Data Table: idnt1a12b13c24d25e31f3 the data I want to obtain is grouped according to t: {code...} after I use groupby, only one data table is obtained for each category, instead of all data tables:
Id n t
1 a 1
2 B 1
3 c 2
4 d 2
5 e 3
1 f 3

The data I want to obtain is grouped by t as follows:

  [      1=>[          0=>[              'id'=>1,              'n'=>'a',              't'=>1          ],          1=>[              'id'=>2,              'n'=>'a',              't'=>1          ]      ]   ]

After I use group by, each category will only get one data, not all

Reply content:

Data Table:
Id n t
1 a 1
2 B 1
3 c 2
4 d 2
5 e 3
1 f 3

The data I want to obtain is grouped by t as follows:

  [      1=>[          0=>[              'id'=>1,              'n'=>'a',              't'=>1          ],          1=>[              'id'=>2,              'n'=>'a',              't'=>1          ]      ]   ]

After I use group by, each category will only get one data, not all

Group by only returns the first data. If you want to return the field information in the group, you can use the following SQL

select id,user_id,GROUP_CONCAT(`order_no`) ,count(`id`) from `table` group by `user_id`

GROUP_CONCAT: You can query all the values that need to be listed and put them in a field separated by commas.

You can use Order by to traverse groups in php.
Another method is group_concat + concat, for example
Select t, concat ('[', group_concat (concat ('{id :',id, ', N :"',n, '"}'), ']') As details fromtableGroupt
This should be similar
1 [{id: 1, n: "a"}, {id: 2, n: "a"}] this record, you just need json_decode.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.