MySQL group_concat()按case语句值排序

时间:2015-07-08 20:27:38

标签: 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

我想做这样的事情,但它不起作用:

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”排序而不使用子查询/嵌套查询?

2 个答案:

答案 0 :(得分:7)

您可以通过列位置而非列名称进行排序来完成此操作。

对于您的案例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

答案 1 :(得分:0)

会话变量可能有效,但我不确定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
;

如果这不起作用,您可以尝试在ORDER BY部分中进行分配,只需在预订单BY中使用@new_name。