问题
In a MySQL group_concat()
clause, I'm trying to order the resulting values of a case statement. The following query configuration properly orders things.name
but does not order the 'Non-US' or 'Unknown' values within the same context.
SELECT
things.id
,group_concat(DISTINCT
CASE
WHEN things.name <> 'United States' THEN 'Non-US'
WHEN things.name IS NULL THEN 'Unknown'
ELSE things.name
END
ORDER BY name SEPARATOR ', ')
FROM things
GROUP BY things.id
I want to do something like this, but it's not working:
SELECT
things.id
,group_concat(DISTINCT
(CASE
WHEN things.name <> 'United States' THEN 'Non-US'
WHEN things.name IS NULL THEN 'Unknown'
ELSE things.name
END) AS new_name
ORDER BY new_name SEPARATOR ', ')
FROM things
GROUP BY things.id
Is there a way to sort by "new_name" without using sub-queries/ nested queries?
回答1:
You can accomplish this by ordering by column position instead of column name.
For your case ORDER BY 1
should work.
SELECT
things.id
,group_concat(DISTINCT
CASE
WHEN things.name <> 'United States' THEN 'Non-US'
WHEN things.name IS NULL THEN 'Unknown'
ELSE things.name
END
ORDER BY 1 SEPARATOR ', ')
FROM things
GROUP BY things.id
回答2:
A session variable might work, but I am not sure the order of evaluation within a GROUP_CONCAT():
SELECT
things.id
, group_concat(DISTINCT
@new_name := (CASE
WHEN things.name <> 'United States' THEN 'Non-US'
WHEN things.name IS NULL THEN 'Unknown'
ELSE things.name
END
) ORDER BY @new_name SEPARATOR ', ')
FROM things
GROUP BY things.id
;
If that doesn't work, you could try doing the assignment in the ORDER BY section instead, and just using @new_name in the pre-ORDER BY.
来源:https://stackoverflow.com/questions/31303035/mysql-group-concat-ordering-by-case-statement-values