简体   繁体   English

SQLite-在WHERE NOT EXISTS语句中使用无关联的多个值

[英]SQLite - Using Multiple values with no relation in WHERE NOT EXISTS statement

EDIT: Answer was that you had to enable foreign keys upon every connection. 编辑:答案是您必须在每个连接上启用外键。 SQLiteCommand command = new SQLiteCommand("PRAGMA foreign_keys = ON"

I looked all over and didn't see an analogue to my question, so if there is an answer just point me in that direction and I'll move on... 我四处张望,没有看到类似的问题,因此,如果有答案,只需将我指向那个方向,然后我继续前进...

I am trying to make a table that is a relation between two other tables, that stores a value for another table. 我试图制作一个表,该表是其他两个表之间的关系,该表存储另一个表的值。

Let's say the create statements for the tables are: 假设表的创建语句为:

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) )

What I want to do is create an insert statement that only allows the insertion into Third when the FirstID is present in First and the SecondID is present in Second. 我想做的是创建一个插入语句,该语句仅允许在FirstID在First中出现而SecondID在Second中出现时插入到Third中。

Any help on what I can try? 我可以尝试的任何帮助吗? The syntax I have tried (and failed with) is: 我尝试过(但失败了)的语法是:

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)

The foreign key constraints already forbid invalid IDs. 外键约束已经禁止了无效的ID。

But if you want to silently ignore rows with nonexistent IDs, you have to check manually. 但是,如果要静默忽略ID不存在的行,则必须手动进行检查。 Your second query is correct, but it cannot have more than one WHERE clause: 您的第二个查询是正确的,但不能有多个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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM