MySQL: Insert if foreign key exists

▼魔方 西西 提交于 2019-12-22 05:06:08

问题


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 could write a php script, but I'd prefer a MySQL solution here.


回答1:


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;


来源:https://stackoverflow.com/questions/3117734/mysql-insert-if-foreign-key-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!