开发者

MySQL: Insert if foreign key exists

开发者 https://www.devze.com 2023-01-05 04:53 出处:网络
I have an Excel sheet with around 2.000 rows that I want to insert into my database. The problem is that the table I want to insert the 2.000 rows into has a column that references to a foreign key i

I have an Excel sheet with around 2.000 rows that I want to insert into my database.

The problem is that the table I want to insert the 2.000 rows into has a column that references to a foreign key in another table. Unfortunately a lot of queries fail, since the provided foreign key value does NOT exist.

I know that I can ignore foreign key checks, but this is not what I want. I don't want to ignore foreign key checks, I just want bad queries not to be executed.

Example:

INSERT INTO test (id, value) VALUES (10, 20);  
INSERT INTO test (id, value) VALUES (20, 20);

The first query fails, since TEST.id references foobar.id and there is no foobar.id = 10. However, the second query would work, since foobar.id = 20 exists, but the second query won't be executed, because the first one already failed.

Is there any way I don't get an error on the first query and my other queries will still be executed?

I 开发者_JAVA技巧could write a php script, but I'd prefer a MySQL solution here.


You could change to insert the result of a select, so something like:

INSERT INTO test (id, value) 
SELECT foobar.id, 20
FROM foobar WHERE id = 10;
0

精彩评论

暂无评论...
验证码 换一张
取 消