使用复合主键删除另一个表中不存在的行

时间:2016-02-08 17:51:28

标签: sqlite sql-delete composite-primary-key

我正在使用SQLite,并且正在尝试将旧行从学生表移到Students_Old,并从Students_Import复制新行。

问题是我有多个主键:

CREATE TABLE "Students" (
`LastName`  TEXT NOT NULL,
`FirstName` TEXT NOT NULL,
`BornDate`  TEXT NOT NULL,
`Class` TEXT NOT NULL,
`Photo` TEXT,
`ValidUntil`    CHAR(10),
PRIMARY KEY(LastName,FirstName,BornDate))

所有表都具有此结构(除了缺少Photo和ValidUntil的Students_Import)。

到目前为止,我已设法用以下方法复制旧行:

INSERT INTO Students_Old 
SELECT DISTINCT a.LastName, a.FirstName, a.BornDate, a.Class, a.Photo, a.ValidUntil FROM
Students a LEFT JOIN Students_Import b ON a.LastName =b.LastName AND a.FirstName=b.FirstName AND a.BornDate=b.BornDate WHERE b.LastName is NULL;

用这个添加新行:

INSERT INTO Students 
SELECT DISTINCT a.LastName, a.FirstName, a.BornDate, a.Class, "", "" FROM 
Students_Import a LEFT JOIN Students b ON a.LastName =b.LastName AND a.FirstName=b.FirstName AND a.BornDate=b.BornDate WHERE b.LastName is NULL

但我无法弄清楚如何删除学生中的旧行(在Students_Import中不存在)。

我尝试了一些这方面的变种:

DELETE FROM Students WHERE (LastName, FirstName, BornDate) IN
(SELECT DISTINCT a.LastName, a.FirstName, a.BornDate, a.Class, a.Photo, a.ValidUntil FROM 
Students a LEFT JOIN Students_Import b ON a.LastName =b.LastName AND a.FirstName=b.FirstName AND a.BornDate=b.BornDate WHERE b.LastName is NULL);

但我只是语法错误,或者我不能在多行上使用它。

我将不胜感激任何帮助!

2 个答案:

答案 0 :(得分:0)

IN不适用于多列。

要查找另一个表中不存在的行,请使用带有correlated subquery的NOT EXISTS:

DELETE FROM Students
WHERE NOT EXISTS (SELECT 1
                  FROM Students_Import
                  WHERE Students_Import.LastName  = Students.LastName
                    AND Students_Import.FirstName = Students.FirstName
                    AND Students_Import.BornDate  = Students.BornDate);

答案 1 :(得分:-1)

我认为你在IN子句中可以有多个列。

怎么样: man pandoc