我正在尝试将几个字段连接成一个字段,但只在结果字符串中保留唯一值。
示例:
title_orig | title_fr | title_de | title_it
---------------------------------------------------------------------
KANDAHAR | KANDAHAR | REISE NACH KANDAHAR | VIAGGO A KANDAHAR
SCREAM 2 | SCREAM 2 | SCREAM 2 | SCREAM 2
CONCAT_WS(', ', title_orig, title_fr, title_de, title_it) AS titles
我会得到
titles
------------------------------------------------------------
KANDAHAR, KANDAHAR, REISE NACH KANDAHAR, VIAGGO A KANDAHAR
SCREAM 2, SCREAM 2, SCREAM 2, SCREAM 2
但我想得到
titles
------------------------------------------------
KANDAHAR, REISE NACH KANDAHAR, VIAGGO A KANDAHAR
SCREAM 2
在PostgreSQL中,我使用了plperl存储过程(%seen=(); return join(", ", grep {$_ && ! $seen{$_}++} @_
)。
我怎样才能摆脱MySQL的重复?
答案 0 :(得分:1)
需要一些工作:
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
...
答案 1 :(得分:0)
使用group_concat()
有另一种解决方案,但它也非常麻烦:
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;