在一个MySQLgroup_concat()子句中,我试图对case语句的结果值进行排序。以下查询配置things.name在同一上下文中正确排序但不对“非美国”或“未知”值进行排序。
group_concat()
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
我想做这样的事情,但是不起作用:
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
有没有一种方法可以通过“ new_name”进行排序而不使用子查询/嵌套查询?
您可以通过按 列位置 而不是 列名 进行排序来完成此操作。
对于您的情况ORDER BY 1应该有效。
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