大家好,博士后专家们,

我有users张桌子

id email
1 john@example.com
2 John@example.com

还有posts张桌子

id userId content
1 1 foo
2 2 bar

忽略大小写时,两个用户的邮箱是相同的,因此我正在寻找一种方法,删除包含重复邮箱的行,并更新posts表中的userId,以指向剩余的用户.

因此,最终结果将是:

id email
1 john@example.com
id userId content
1 1 foo
2 1 bar

我不关心我最终得到的邮箱地址的版本(即不必是全小写的).

最好的方法是什么?

推荐答案

您可以使用最小的id更新posts表:

update posts p
  set userid = u.user_id
from (
  select min(id) user_id, array_agg(id) as user_ids
  from users u
  group by lower(email)
  having count(*) > 1
) u
where p.userid = any(u.user_ids)
  and p.userid <> u.user_id
;

派生表中的SELECT返回具有多个邮箱地址的所有用户.WHERE子句随后更新posts表以使用其中一个ID.完成后,您可以删除不再使用的用户

delete from users
where not exists (select * 
                  from posts p 
                  where users.id = p.userid);

Online example

Postgresql相关问答推荐

一列引用两个不同的表

如何在PostgreSQL 16中设置&Q;VARSIZE&Q;和&Q;SET_VARSIZE&Q;

将列类型从文本[]更改为jsonb[]

PostgreSQL无效语法

Gorm 中的更新将created_at、updated_at 作为默认时间

如何在docker-compose中使用docker secrets设置ConnectionString?

在 postgres/presto/AWS-Athena 中,与 array_agg( (col1, col2) ) 相反的是什么来获得每组多行?

如何在 kubernetes 中安全地重启 postgresql 容器?

PL/pgSQL 中 PL/SQL %ISOPEN 的类似功能是什么?

为什么这里的默认格式不同? (ISO 8601 的两种不同实现)

使用 postgresql Select 整数作为位和状态表

Rails 迁移:PostgreSQL 上的 Bigint 似乎失败了?

Postgres COPY FROM csv file-No such file or directory

Select 空字段

H2 postgresql mode模式似乎不起作用

用于更改 postgresql 用户密码的 bash 脚本

PostgreSQL 条件 where 子句

根据 Helm 图表设置值

如何在 postgres 查询中排名

如何在不丢失openproject数据的情况下将postgresql数据库从10升级到12