mysql concat_ws without duplicates

我只是一个虾纸丫 提交于 2020-01-02 08:23:04

问题


I am trying to concatenate a few fields into a single one, but only keep unique values in the resulting string.

Example:

title_orig | title_fr   | title_de                | title_it
---------------------------------------------------------------------
KANDAHAR   | KANDAHAR   | REISE NACH KANDAHAR     | VIAGGO A KANDAHAR
SCREAM 2   | SCREAM 2   | SCREAM 2                | SCREAM 2

With CONCAT_WS(', ', title_orig, title_fr, title_de, title_it) AS titles I would get

titles
------------------------------------------------------------
KANDAHAR, KANDAHAR, REISE NACH KANDAHAR, VIAGGO A KANDAHAR
SCREAM 2, SCREAM 2, SCREAM 2, SCREAM 2

But I would like to get

titles
------------------------------------------------
KANDAHAR, REISE NACH KANDAHAR, VIAGGO A KANDAHAR
SCREAM 2

In PostgreSQL, I used a plperl stored procedure (%seen=(); return join(", ", grep {$_ && ! $seen{$_}++} @_).

How could I get rid of the duplicates in MySQL?


回答1:


Needs a bit of work:

SELECT 
  CONCAT(
    title_orig,
    IF(title_fr=title_orig,'',CONCAT(', ',title_fr)),
    IF(title_de=title_orig OR title_de=title_fr,'',CONCAT(', ',title_de)),
    IF(title_it=title_orig OR title_it=title_fr OR title_it=title_de,'',CONCAT(', ',title_it))
  ) AS title_concat
FROM
  ...



回答2:


There is an alternative solution using group_concat(), but it is also quite cumbersome:

SELECT id, group_concat(
  DISTINCT titles
  ORDER BY titles
  SEPARATOR ', ')
FROM (
  SELECT id, title_orig AS titles FROM test
  UNION ALL SELECT id, title_fr FROM test 
  UNION ALL SELECT id, title_de FROM test 
  UNION ALL SELECT id, title_it FROM test
) AS tmp
GROUP BY id;


来源:https://stackoverflow.com/questions/9485901/mysql-concat-ws-without-duplicates

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