带有if语句的SQL INSERT

时间:2012-03-26 21:43:25

标签: python mysql sql

我有一个名为notification的表,有两列:

  • 提供商
  • 电子邮件

值如下所示:

  • apple | apple@apple.com
  • nbc | nbc@nbc.com
  • nbc | me@me.com
  • abc | abc@abc.com
  • abc | me@me.com

对于没有电子邮件me@me.com的所有提供商,我想在提供商和电子邮件them@them.com中插入另一行。例如,在上面的查询中,INSERT语句的结果为:INSERT INTO notification VALUES ('apple', 'them@them.com')

我有一个包含数千行这样的表,如何编写这样的INSERT语句?

2 个答案:

答案 0 :(得分:2)

INSERT INTO notification
SELECT DISTINCT provider, 'them@them.com'
FROM notification
WHERE provider NOT IN
(SELECT DISTINCT provider
FROM notification
WHERE email = 'me@me.com')

答案 1 :(得分:0)

这可以让你得到你想要的东西:

insert into notification (provider, email)
select distinct provider, 'them@them.com'
from notification
where provider not in (
        select provider
        from notification
        where email like 'me@me.com'
    )