开发者

SQL Insert if NULL

Is there a purely SQL way to do开发者_运维百科 this?

I have a table apples: id, price, and another apple_info: apple_id, color

For each row in apples, I want to add a corresponding row in apple_info, if it does not already exist. Can't find any examples of this.


Try this:

insert into apple_info (apple_id, color)
select a.id, 'some_color'
  from apples a
  left outer join apple_info ai
    on (a.id = ai.apple_id)
 where ai.apple_id is null;

You will insert a row on apple_info with non existent apple_id and a fixed value for color. I guess this is what you want.


Use INSERT IGNORE:

INSERT IGNORE INTO apple_info(apple_id, color)
    SELECT id, 'green' FROM apples
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜