我想连接3个包含用户名的字段并用逗号分隔它们,但前提是它们不是空白的。最后寻找独特的名字。
我找到了一个函数CONCAT_WS,它将连续检查NULL而不是空白。
Example:
Input : A B C => A,B,C
Input : A '' C => A,C
Input : A C C => A,C
你会建议一个解决方案吗?
答案 0 :(得分:1)
您可以使用GROUP_CONCAT
这样做:
SELECT t.`id`,GROUP_CONCAT(distinct t.cols SEPARATOR ',')
FROM (SELECT `id`,col1 as cols FROM YourTable where col1 is not null and col1 <> ''
UNION ALL
SELECT `id`,col2 as cols FROM YourTable where col2 is not null and col2 <> ''
UNION ALL
SELECT `id`,col3 as cols FROM YourTable where col3 is not null and col3 <> '' ) t
GROUP BY t.`id`
答案 1 :(得分:1)
您可以动态规范化表格,然后使用group_concat
:
select id, group_concat(username order by username) as userlist
from (
select distinct t.id,
case
when n.i = 1 then t.user1
when n.i = 2 then t.user2
when n.i = 3 then t.user3
end as username
from table1 t
cross join (select 1 i union all select 2 union all select 3) n
having username <> ''
) normalized
group by id
http://sqlfiddle.com/#!9/89281/2
这是另一个按列而不是名字命名用户名的方法:
select t.*, group_concat(distinct
case
when n.i = 1 and t.user1 <> '' then t.user1
when n.i = 2 and t.user2 <> '' then t.user2
when n.i = 3 and t.user3 <> '' then t.user3
end
order by n.i
) as userlist
from table1 t
cross join (select 1 i union all select 2 union all select 3) n
group by t.id
答案 2 :(得分:0)
CONCAT_WS(',',NAME_COL1, IF(NAME_COL2, IF(NAME_COL2!=NAME_COL1,NAME_COL2,NULL),NULL),IF(NAME_COL3, IF(NAME_COL3!=NAME_COL1,NAME_COL3,NULL),NULL))