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 t
group 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.
EDIT:
You can use group_concat()
multiple times:
select a, group_concat(b) as bs, group_concat(c) as cs
from t
group by a;
Or, combine it with concat()
:
select a, group_concat(concat(b, ':', 'c')) as bcs
from t
group 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.