Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Insert if foreign key exists

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.

like image 276
user375700 Avatar asked Jun 25 '10 11:06

user375700


1 Answers

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;
like image 110
Rowland Shaw Avatar answered Oct 16 '22 05:10

Rowland Shaw