Mysql合并两个varchar列删除重复的单词

时间:2018-05-19 20:39:58

标签: mysql sql merge

我有2个varchar列的表 - col_name1和col_name2 PLUS空varchar col_name3

event

请参阅SQLFIDDLE

我正在寻找一种方法将两个varchar列合并为一个但删除重复的单词。 这意味着新的col_name3应该只包含如下所示的唯一单词

(1, 'hello world', 'hello test', ''),
(2, 'hello from my sql fiddle', 'hello my sql', '');

1 个答案:

答案 0 :(得分:1)

以下是问题的解决方案:

select id,group_concat(words) output
from(
SELECT id,SUBSTRING_INDEX(SUBSTRING_INDEX(t.col, ' ', x.cifre), ' ', -1) AS words
,count(1)
FROM (SELECT id,concat(col_name1,' ',col_name2,' ',col_name3) as col FROM table_name) t
INNER JOIN
(
    SELECT 1 + a.i + b.i * 10  cifre, b.i + a.i * 10  sute
    FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) a
    CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) b
) x
ON (LENGTH(t.col) +1 - LENGTH(REPLACE(t.col, ' ', ''))) >= x.cifre
group by id,SUBSTRING_INDEX(SUBSTRING_INDEX(t.col, ' ', x.cifre), ' ', -1)
having count(1) =1) s
where length(words) > 0
group by id

输出:

id  output
1   test,world
2   fiddle,from

http://sqlfiddle.com/#!9/942f8/27