Cam
Cam

Reputation: 15245

Conditionally insert a row

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?

Upvotes: 0

Views: 418

Answers (2)

Francisco Soto
Francisco Soto

Reputation: 10402

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.

Upvotes: 3

mindas
mindas

Reputation: 26733

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?

Upvotes: 0

Related Questions