简体   繁体   中英

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.

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.

But is that 2 query execution? how it should be written? I tried 2 sql execution the second - where insert into FK, has failed.

I've put the 3 methods discussed in the comments into a SqlFiddle here

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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