更新基于相同列值组合行的表

时间:2019-11-30 10:51:48

标签: database sqlite

我有一个名为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
);

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 || ',%'  
);