Group concat is driving me nuts.
I have 1 table 2 columns
FRUIT QUANTITY
APPLE 4
ORANGE 6
I'd like to group concat these into one field
orange:4, apples:6
Group concat is driving me nuts.
I have 1 table 2 columns
FRUIT QUANTITY
APPLE 4
ORANGE 6
I'd like to group concat these into one field
orange:4, apples:6
You can concat()
both columns for each row, then group_concat()
the results over all rows:
select group_concat(concat(fruit, ':', qty) separator ', ') res from mytable
You might want to consider adding an order by
to group_concat()
in order to get predictable, consistent results.
You can list multiple columns and other values in the GROUP_CONCAT()
call, and it will concatenate them together.
SELECT GROUP_CONCAT(fruit, ':', qty SEPARATOR ', ') AS fruits
FROM yourTable
If you have lots of columns that you're joining like this, you could use CONCAT_WS()
to concatenate them all together with the same delimiter. See GROUP_CONCAT multiple columns as an array or exolodable string