编辑:答案是你必须在每次连接时启用外键。
SQLiteCommand command = new SQLiteCommand("PRAGMA foreign_keys = ON"
我全神贯注地看到了与我的问题类似的东西,所以如果有答案,请指出我的方向,我会继续......
我正在尝试创建一个表,这是另外两个表之间的关系,它存储另一个表的值。
让我们说表的create语句是:
CREATE TABLE First ( FirstID Integer PRIMARY KEY, Name Text, otherThing Text)
CREATE TABLE Second ( SecondID Text PRIMARY KEY, OtherStuff VarChar(10) )
CREATE TABLE Third ( FirstID Integer, SecondID Text, SomeData Text,
FOREIGN KEY (FirstID) REFERENCES First(FirstID),
FOREIGN KEY (SecondID) REFERENCES Second(SecondID),
PRIMARY KEY ( FirstID, SecondID) )
我想要做的是创建一个insert语句,当FirstID出现在First时,只允许插入到Third,SecondID出现在Second中。
对我可以尝试的任何帮助?我尝试过的语法(失败了)是:
INSERT INTO Third (FirstID, SecondID, SomeData) SELECT 123, "foo", "Interesting Data Here" WHERE EXISTS ( SELECT FirstID FROM First AND SELECT SecondID FROM Second)
INSERT INTO Third (FirstID, SecondID, SomeData) SELECT 123, "foo", "Interesting Data Here" WHERE EXISTS ( SELECT FirstID FROM First) AND WHERE EXISTS( SELECT SecondID FROM Second)
答案 0 :(得分:0)
外键约束已禁止无效ID。
但是如果要静默忽略ID不存在的行,则必须手动检查。 您的第二个查询是正确的,但它不能有多个WHERE子句:
INSERT INTO Third (FirstID, SecondID, SomeData)
SELECT 123, 'foo', 'Interesting Data Here'
WHERE EXISTS (SELECT 1 FROM First WHERE FirstID = 123)
AND EXISTS (SELECT 1 FROM Second WHERE SecondID = 'foo');