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

时间:2014-06-04 09:28:32

标签: 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"

详细说明:仍然从account表中引用了Key(id)=(8225700)。

但真正的行有引用,我无法删除它。

如何删除这些损坏的行?

2 个答案:

答案 0 :(得分:1)

// 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的完整输出。

答案 1 :(得分:0)

听起来像是一个糟糕的索引。尝试重建索引。

reindex table users
相关问题