开发者

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?


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜