MySQL Query grouping

Source: Internet
Author: User
Data sheet:
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 extract is grouped by T:

  [      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 sheet:
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 extract is grouped by T:

  [      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 is the only one that returns the first data. If you want to return field information in a 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 This can be queried for all values that need to be listed, and placed in a field, separated by commas.

You can use order by and then traverse the grouping in PHP
The other way is Group_concat + concat, like
Select T, concat (' ['), Group_concat (Concat (' {id: ', ', ' N: ', ', ' id n } ')), '] ') as details from table GROUP byt
This should be to get a similar
1 [{id:1,n: "a"},{id:2,n: "A"}] this kind of record, you json_decode.

  • Related Article

    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.