我有一个名为table
的表,如下所示:
| id | name | city |
|----|-------|---------|
| 0 | Rose | Madrid |
| 1 | Alex | Lima |
| 2 | Rose | Sidney |
| 3 | Mario | Glasgow |
我需要更新该表,以便将共享同一name
的两行合并为一个新行并删除。
| id | name | city |
|----|-------|----------------|
| 1 | Alex | Lima |
| 3 | Mario | Glasgow |
| 4 | Rose | Madrid, Sidney |
我不在乎是否必须在几个SQL语句中完成。
到目前为止,我所做的只是列出受此影响的行。
SELECT *
FROM table
WHERE name IN (
SELECT name
FROM table
GROUP BY name
HAVING COUNT(*) > 1
);
答案 0 :(得分:1)
假设Test
是自动递增主键,则需要一个id
和一个INSERT
语句:
DELETE
请参见demo。
结果:
insert into tablename(name, city)
select name, group_concat(city, ',')
from tablename
group by name
having count(*) > 1;
delete from tablename
where instr(name, ',') = 0
and exists (
select 1 from tablename t
where t.id <> tablename.id and t.name = tablename.name
and ',' || t.city || ',' like '%,' || tablename.city || ',%'
);