sql - 主键的顺序扫描和索引扫描返回不同的行

标签 sql postgresql

我的表 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/

相关文章:

sql - MySQL中DELIMITER和DECLARE的使用?

sql - 如何在SQL中仅在一个字段上选择不重复的记录?

mysql - 我是 sql 新手,我正在使用 mysql,我不能使用复制表并创建本地临时表和全局临时表

java - 从 UNKNOWN 到 UNKNOWN 的转换是不支持的异常(在用于迁移的 Java 程序中)

sql - PostgreSQL 根据 case 语句选择列

sql - 为什么人们在 SQL 中使用 ASC?

sql - 给定日期的有效价格

sql - 如何统计组数?

sql - 在 Postgresql 中以间隔添加日期作为参数的准备语句

python - psycopg2 无法插入特定列