MySQL Group by one column, but select all data

后端 未结 3 1412
无人共我
无人共我 2021-01-12 04:42

I\'ve got a database which contains lots of data. I would like to select all data, but Group by one column.

So for example:

column a | column b
examp         


        
3条回答
  •  余生分开走
    2021-01-12 05:22

    All SQL systems deal in tables: rectangles of data with rows and columns. Your question asks for a result set which isn't really a rectangle of data, in the sense that it contains "header" rows and "detail" rows.

     Example:    (header row)
       - apple   (detail row)
    

    It's common practice to create such header / detail breakout in your client (php) software.

    Pro tip: Remember that if you don't specify ORDER BY, MySQL (and all SQLs) are permitted to return the information in your result in any convenient order. Enlarging on Gordon's fine answer, then, you might want:

     SELECT a, 
            GROUP_CONCAT(CONCAT(b, ':', 'c') ORDER BY b,c) AS bcs
       FROM t
      GROUP BY A
      ORDER BY A
    

    I learned this the hard way when I helped write a SQL app that was really successful. All the ordering worked great until we switched over to higher - capacity clustered access methods. Then lots of "default" ordering broke and our customers saw strange stuff until we fixed it.

提交回复
热议问题