[英]insert into foreign key proper sql execution
I found that my error caused by my PK doesn't have a value so my insertion on FK failed. 我发现我的PK引起的错误没有值,因此我在FK上插入失败。
like table A uId is PK of table B's uId (FK), so if I want to insert 1 in table B's uId, the table A's uId must have the value of 1. 像表A的uId是表B的uId(FK)的PK,因此,如果我想在表B的uId中插入1,则表A的uId必须具有值1。
But is that 2 query execution? 但是那是2查询执行吗? how it should be written? 应该怎么写? I tried 2 sql execution the second - where insert into FK, has failed. 我第二次尝试了2条sql执行-插入FK失败。
I've put the 3 methods discussed in the comments into a SqlFiddle here 我将注释中讨论的3种方法放到了SqlFiddle中
-- Null Foreign Key, if the relationship is optional
INSERT INTO B(AID) VALUES(NULL);
-- Lookup - if you know of another `natural` column in table A,
-- e.g. here we know the Name we need to link to
INSERT INTO B(AID) VALUES((SELECT AID FROM A WHERE AName = 'Foo'))
-- Identity Insert - when A and B are inserted at the same time,
-- and you need to pass A ID to B
INSERT INTO A(AName) VALUES('Baz');
INSERT INTO B(AID) VALUES((SELECT SCOPE_IDENTITY()));
SELECT * FROM A;
SELECT * FROM B;
For MySql it is similar, just use LAST_INSERT_ID()
vs SCOPE_IDENTITY()
对于MySql,它是类似的,只使用LAST_INSERT_ID()
vs SCOPE_IDENTITY()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.