MySQL group_concat() ordering by case statement values

a 夏天 提交于 2019-12-13 02:34:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!