The error message that your client introduces can be a source of confusion. IntelliJ reported this message in the comment thread you were talking about, but I ran your well-defined test tables in both MySQL 5.6.35 and 5.7.16-ubuntu, and in both versions the statement in question reported 0 lines affected:
mysql > INSERT INTO Test_Child(fid) -> SELECT id -> FROM Test_Parent -> WHERE dummy = 'missing value'; Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0
So, looking at the message about the affected rows affected, what is actually happening here is that the SELECT
part of your INSERT...SELECT
does not contain rows, and therefore MySQL is not trying to insert any row. Consequently, there was no violation of foreign key restrictions.
The format of INSERT INTO...SELECT
slightly different from your later example:
INSERT INTO Test_Child(id, fid) VALUES (123, (SELECT id FROM Test_Parent WHERE dummy = 'missing value'));
... because in this case, the numeric literal 123
forces one line to be inserted, and it matches the null
value returned from the subquery. So null
tries to insert and causes a constraint violation.
If you force INSERT...SELECT
return a row with a null value, you may crash due to a violation of the constraint:
INSERT INTO Test_Child (fid) -- Return a literal NULL row... SELECT NULL as id FROM Test_Parent -- Column fid cannot be null
source share