Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL INSERT INTO... SELECT - How to determine which select clauses result in NULL?
    primarykey
    data
    text
    <p>I'm trying to insert a row into a table which references keys in other tables. There are instances where the insert/select will fail because the selected value can not be null. I'd like to know which selects fail so that I can create the necessary rows in other tables as needed. </p> <p>The following example is a bit contrived, but should illustrate the challenge here:</p> <pre><code>CREATE TABLE TableOne ( TableOneId INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, Value VARCHAR(64) NOT NULL ) ENGINE=InnoDB; CREATE TABLE TableTwo ( TableTwoId INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, Value VARCHAR(64) NOT NULL ) ENGINE=InnoDB; CREATE TABLE DependentTable ( DependentId INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, TableOneId INT UNSIGNED NOT NULL, TableTwoId INT UNSIGNED NOT NULL, Value FLOAT NOT NULL, FOREIGN KEY (TableOneId) REFERENCES TableOne(TableOneId), FOREIGN KEY (TableTwoId) REFERENCES TableOne(TableTwoId) ) ENGINE=InnoDB; INSERT INTO DependentTable (Value, TableOneId, TableTwoId) SELECT 1.0, TableOne.TableOneId, TableTwo.TableTwoId FROM TableOne,TableTwo WHERE TableOne.Value='TableOneValue' AND TableTwo.Value='TableTwoValue'; Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0 </code></pre> <p>If either 'TableOneValue' or 'TableTwoValue' doesn't exist, then the select will return null and 0 rows will be inserted - as expected. However, I was hoping to get some other piece of information that would allow me to determine which value didn't exist so I can create it.</p> <p>The problem, at least in my actual situation, is that blindly creating each value to satisfy the foreign key reference would be overkill/expensive as there are multiple foreign keys and some of those dependent tables will have other required dependencies. I'd like to approach it a little more intelligently and determine which reference(s) didn't exist and only create those instead.</p> <p>I could try to create the rows in dependent tables one-by-one, wait until a row is actually inserted ( versus getting a duplicate entry ), and then try the original insert again - but it feels like there should be a better/more elegant way to do this...</p> <p>Thanks in advance for any suggestions/ideas...</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload