我的表 users
中的数据有问题。该表的主键定义为:
"primary_c26a3d1a9d1c7aa4bb0a8d6b752c01a7" PRIMARY KEY, btree (id)
当我使用 WITH
子句强制对表进行顺序扫描时,我发现了重复的 ID:
=> WITH temp_table AS (select * from "users") SELECT id from temp_table group by id having count(id) > 1;
-[ RECORD 1 ]
id | 8225700
-[ RECORD 2 ]
id | 8225682
...
这是怎么发生的?如果我按索引搜索这些重复项,我不会遇到同样的问题:
=> select count(*) from users where id = 8225700;
-[ RECORD 1 ]
count | 1
我正在使用 PostgreSQL 9.1。
VACUUM 没有帮助我。我试图通过 ctid 删除重复项:
// good and bad rows
> with usrs as (select ctid, * from users) select ctid, id from usrs where id = 8225700;
ctid | id
-------------+---------
(195669,33) | 8225700
(195708,34) | 8225700
// good row
select id, ctid from users where id = 8225700;
-[ RECORD 1 ]-----
id | 8225700
ctid | (195708,34)
// deleting bad row
DELETE FROM users WHERE ctid = '(195669,33)';
ERROR: update or delete on table "users" violates foreign key constraint "foreign_1589fcbc580d08caf03e0fbaaca7d6dd" on table "account"
详细说明:Key (id)=(8225700) 仍然从 account
表中引用。
但是真正的行有引用,我不能删除它。
如何删除这些断行?
最佳答案
// deleting bad row DELETE FROM users WHERE ctid = '(195669,33)'; ERROR: update or delete on table "users" violates foreign key constraint "foreign_1589fcbc580d08caf03e0fbaaca7d6dd" on table "account" In detail: Key (id)=(8225700) is still referenced from table "account".
它说得很清楚:该行被 account
表引用。
您需要找到引用并修复它。
UPDATE account SET fkey_field = ??? WHERE ... ;
细节取决于account
表的结构和内容。
如果您需要更多帮助,请粘贴 psql 中 \d account
和 \d users
的完整输出。
关于sql - 主键的顺序扫描和索引扫描返回不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24033754/