SQLite外键约束'忽略额外数据'

时间:2018-01-25 21:47:18

标签: database sqlite foreign-keys constraints

我需要创建2个包含以下数据的表。父表A的列idPrimary Key

A

+----+--------+
| id | Animal |
+----+--------+
| 1  | Dog    |
| 2  | Monkey |
| 3  | Bear   |
| 4  | Tiger  |
+----+--------+

另一个表B有一个外键id1,引用表id的键A

B

+-----+---------+
| id1 | Desc    |
+-----+---------+
| 1   | barks   |
| 2   | jumps   |
| 3   | attacks |
| 4   | roars   |
| 5   | eats    |
+-----+---------+

我可以创建表A并插入数据。我可以创建表B,但是当我尝试在表5中插入数据(具有额外值B)时,它会给出错误SQLITE_CONSTRAINT(787): FOREIGN KEY constraint failed这是显而易见的。我的问题是如何让SQLite只插入符合主键的数据,并忽略导致表C

中所见输出的额外数据

C

+-----+---------+
| id1 | Desc    |
+-----+---------+
| 1   | barks   |
| 2   | jumps   |
| 3   | attacks |
| 4   | roars   |
+-----+---------+

我尝试运行的SQLite查询如下所示:

PRAGMA foreign_keys=OFF;
CREATE TABLE temp_tbl AS SELECT * FROM TableB;
DROP TABLE TableB;
CREATE TABLE TableB (id1 INTEGER REFERENCES TableA(id) ON UPDATE CASCADE ON DELETE CASCADE,Desc VARCHAR); 
INSERT INTO TableB(id1,Desc) SELECT id1,Desc FROM temp_tbl;
DROP TABLE temp_tbl;
PRAGMA foreign_keys=ON;

1 个答案:

答案 0 :(得分:0)

仅插入匹配的行:

XMLName xml.Name