views:

40

answers:

2

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?

A: 

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?

mindas
+3  A: 
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.

Francisco Soto
+1: You beat me, and I like yours better.
OMG Ponies
Can you explain in more detail how this works? Perhaps I don't understand `select` well enough, but how can it do that?
Cam
@incrediman: The values in the SELECT are statically defined - they aren't values that exist in TABLE_B
OMG Ponies
Basically that syntax is there so you can insert rows into one table from other tables, but since you can use constant values you don't actually have to use the table(s) values you queried. Still, if the query does not return any rows, no row will be inserted, so you can use that tool to conditionally insert depending on values on other tables as the example you used.
Francisco Soto
+1 just typed exactly the same query as your answer poped up.
SchlaWiener
Thanks everyone. Also, is this definitely the correct syntax? No other brackets etc? Isn't VALUES(...) usually required?
Cam
Nevermind - I was only wondering as I was receiving an error I thought was related to the syntax provided here, but it was from something else in my query. Thanks again!
Cam