MySQL Group by one column, but select all data MySQL Group by one column, but select all data sql sql

MySQL Group by one column, but select all data

I think you can get what you want using group_concat():

select a, group_concat(b)from tgroup by a;

This will create a list of "b"s for each a. In your example:

example    apple,pear,orange,strawberry

You can change the separator using the SEPARATOR keyword.


You can use group_concat() multiple times:

select a, group_concat(b) as bs, group_concat(c) as csfrom tgroup by a;

Or, combine it with concat():

select a, group_concat(concat(b, ':', 'c')) as bcsfrom tgroup by a;

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.

The example live of accordion: implement in code below. ;)

The code to mount data:

<html>    <head>Your page</head>    <body>        <div class="accordion">            <?php echo getData() ?>        </div>    </body></html><?phpfunction getData(){    //This get the unique values of column a    $sql = "SELECT DISTINCT column_a FROM table";    $result = mysql_query($sql) or die(mysql_error());    while ($row = mysql_fetch_object($result)) {        $html = "<h3>{$row->column_a}</h3>";        //This get the values with column a some value        $sql2 = "SELECT column_b FROM table WHERE column_a LIKE '%{$row->column_a}%'";        $result2 = mysql_query($sql2) or die(mysql_error());        $html .= '<div class="pane"><ul>';        while ($row2 = mysql_fetch_object($result2)) {            $html .= '<li>{$row2->column_b}</li>';        }        $html .= '</ul></div>';    }    return $html;}?>