Tutorial :Conditionally insert a row



Question:

I'd like to insert a row into table A, but only if another row in table B exists. For example something like this...

IF EXISTS (SELECT * FROM B WHERE id=1)      INSERT INTO A          (id, value1, value2)          VALUES (1, 'foo', 'bar')  

However that doesn't work. What will?


Solution:1

INSERT INTO A (value1, value2, value3)      SELECT 'foo', 'bar', 'foo' FROM B WHERE ID = 1  

One potential problem here is if your condition is met more than once it will insert as many rows so adjust your query to that, but it will do what you want, only insert if the conditions on the select are met.


Solution:2

Have a look at this piece of MySQL manual, it gives an example with SELECT, but maybe INSERT would also work in a similar fashion?


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »