search

Home  >  Q&A  >  body text

How to group in mysql?

Assume user table

id name group
1 evan admin
1 evan1 admin
1 evan2 admin
1 evan3 user
1 evan4 user

select * from user group by user.group There are only 2 pieces of data coming out, instead of user.group being a group of admin, user.group is a group of user

Solution,

mysql How to group arrays? It feels like there are many places where grouping is needed.

PHP中文网PHP中文网2704 days ago1070

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-07-04 13:45:47

    I don’t quite understand what you mean. If you use group by user.group, 2 items will appear, because your data only has two kinds of group data: admin and user.

    Grouping needs to be used in conjunction with statistical methods such as count, sum etc.

    If you want the data of admin to be together and the data of user to be together, then just order by user.group is fine

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-07-04 13:45:47

    If you use the GROUP BY clause, if there is only one condition, only all unique values ​​that satisfy the condition will be used, one for each piece of data. For GROUP BY user.group, you only have two unique values: user and admin, so there will only be two pieces of data.

    If you want to put the same user.group data together, as mentioned above, just use sorting.

    If you want to merge the same user.group into one row without losing user.namedata, you can use the GROUP_CONCAT() function to merge the name in all groups into a comma-separated string ( Of course it can be changed to other separators)

    SELECT *, GROUP_CONCAT(user.name) FROM user GROUP BY user.group

    reply
    0
  • Cancelreply