如何删除 SQL 数据库中存在 account_id 重复项的行?

How do I delete rows in a SQL database where there's duplicates of the account_id?

我有一个数据库,其中每一行都由 "account_id" 和 "device_name" 的组合唯一标识(这两个组合在一起使行唯一)。最多应有两个具有特定 "account_id" 的帐户,例如:

account_id: 78, device_name: "Bob",
account_id: 78, device_name: "John"

但我最近引入了一个错误,其中可能有超过 2 个,我想保留所有出现的情况,如上面只有 1 或 2 个的情况,但删除所有出现 3 个或更多的情况(错误现已修复,下次用户登录时会自动修复,不用担心。

例如,这很糟糕,我想删除所有 3 行:

account_id: 39, device_name: "Tim",
account_id: 39, device_name: "Rob",
account_id: 39, device_name: "Sam"

我知道我可以做类似的事情:SELECT COUNT(*) FROM accounts where account_id=89; 它会 return 像 count: 6。此时我会知道这是一个错误,我应该删除与该 ID 匹配的行。

我可以为每个帐户手动检查和执行此操作,但在几十个帐户中它变得非常重复。有没有办法 "chain" 使用另一个命令并按照 "find all rows in the database where the same account_id is in 3 or more rows, and delete those rows"?

的方式说些什么

您可以在 delete:

中使用过滤
delete from t
    where account_id in (select account_id from t group by account_id having count(*) > 2);