I have a group_concat
which returns all the strings from one column. The strings can be variable length. How can I select the first string returned by the group_concat
(where 'first' is defined by a group_concat
ordering clause)?
Here is a simplified example. From a table of vegetable select the cheapest vegetable from each veg type.
From this table:
veg type price ---------------------- carrot root 1.23 turnip root 0.45 sprouts bud 3.56 ...
Select this:
selectedVeg price ------------------- turnip 0.45 sprouts 3.56 ...
My clumsy attempt:
SELECT
SUBSTRING(
GROUP_CONCAT(veg ORDER BY price),
1,
LOCATE(
',',
CONCAT(GROUP_CONCAT(veg order by price), ',')
) - 1
) AS selectedVeg
FROM vegTable
GROUP BY type
So for the root veg type, 'GROUP_CONCAT' will return 'turnip, carrot'. Then the locate finds the first comma. And then substring returns all the characters up to this comma. So "selectedVeg" equals 'turnip'.
I've added a CONCAT
to ensure there is always one comma for the LOCATE
to find.
This doesn't seem very efficient as the GROUP_CONCAT
has to be run twice (and it's quite complicated in my actual problem).
Thanks.