在2个主键上执行删除时出现SQLite错误

时间:2014-06-12 14:55:29

标签: sql sqlite shared-primary-key

我创建了一个包含2个主键的表,当我尝试一次删除少量记录时,整个表都被删除了。这是我尝试的代码,我不知道为什么会这样做。 任何帮助都将受到欢迎。

BEGIN TRANSACTION;
DROP TABLE NAMES1;
/* Create a table called NAMES1 */
CREATE TABLE NAMES1(Id integer, Id2 integer, Name text,PRIMARY KEY(Id,Id2));

/* Create few records in this table */
INSERT INTO NAMES1 VALUES(1,1,'Tom');
INSERT INTO NAMES1 VALUES(2,1,'Lucy');
INSERT INTO NAMES1 VALUES(3,4,'Frank');
INSERT INTO NAMES1 VALUES(4,1,'Jane');
INSERT INTO NAMES1 VALUES(5,6,'Robert');
COMMIT;

/* Display all the records from the table */

SELECT Count(*) FROM NAMES1; /* Returns 5 */
DELETE FROM NAMES1 WHERE (Id AND Id2) in ((2 AND 2),(1 AND 1),(2 AND 1));
SELECT Count(*) FROM NAMES1; /* Returns 0 */

根据我的计算,返回的计数应为3,而不是0。

2 个答案:

答案 0 :(得分:0)

在SQLite中,您无法将多个值与单个表达式进行比较。

删除多个记录的最简单方法是逐个执行:

BEGIN;
DELETE FROM Names1 WHERE Id = 2 AND Id2 = 2;
DELETE FROM Names1 WHERE Id = 1 AND Id2 = 1;
DELETE FROM Names1 WHERE Id = 2 AND Id2 = 1;
COMMIT;

或者,写一个明确检查所有三种组合的条件:

DELETE FROM Names1
WHERE (Id = 2 AND Id2 = 2)
   OR (Id = 1 AND Id2 = 1)
   OR (Id = 2 AND Id2 = 1);

答案 1 :(得分:-1)

行:

DELETE FROM NAMES1 WHERE (Id AND Id2) in ((2 AND 2),(1 AND 1),(2 AND 1));

相当于:

DELETE FROM NAMES1 WHERE 1 in ((1,1,1);

并删除整个表格

将其更改为:

DELETE FROM NAMES1 WHERE Id in (2,1) AND Id2 in (2,1);