s2t*_*2t2 1 mysql sql sql-order-by group-concat
在MySQL group_concat()子句中,我正在尝试对case语句的结果值进行排序.以下查询配置正确things.name排序,但未在同一上下文中排序"非美国"或"未知"值.
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
Run Code Online (Sandbox Code Playgroud)
我想做这样的事情,但它不起作用:
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
Run Code Online (Sandbox Code Playgroud)
有没有办法按"new_name"排序而不使用子查询/嵌套查询?
您可以通过按列位置而不是列名称进行排序来完成此操作.
对于你的情况ORDER BY 1应该工作.
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
Run Code Online (Sandbox Code Playgroud)