MySQL SQL根据相同ID的其他记录的存在将记录添加到表中

时间:2017-10-19 17:51:09

标签: mysql sql

我想知道是否有办法在不使用代码的情况下在MySQL的单个SQL语句中执行此操作。

我有一个表,每行包含id和属性。 Id不是主键,因此可能有多个ID和多个属性:

ID     Attribute    Expiry Date
10001  Attribute 1  10/10/2017
10001  Attribute 2  10/10/2017
10001  Attribute 3  20/12/2017
10002  Attribute 1  04/02/2018
10002  Attribute 3  15/08/2018

在上面的示例中,ID 10002没有属性2.我想为每个具有属性1而不是属性2的ID插入属性2,但是我不想在那里添加属性2该ID不是属性1。此外,属性2应该从属性1中的相同日期中获取它的有效期。

这可以通过选择具有属性1的所有IDS并为ID = ID AND attribute = attribute2选择每个IDI来完成,如果它返回0行则插入新行,但我认为它也可以在纯SQL中完成,可能使用自联接,可能是子选择。

感谢您的帮助!

马特

2 个答案:

答案 0 :(得分:2)

您可以使用not exists执行此操作。

insert into tbl(id,attribute,expiry_date)
select id,'Attribute 2',expiry_date
from tbl t1
where attribute = 'Attribute 1'
and not exists (select 1 from tbl t2
                where t1.id=t2.id and t2.attribute='Attribute 2')

答案 1 :(得分:0)

您可以对带有attribute1的id使用insert select,但不能同时使用属性1和属性2

insert into my_table (id, attribute)
select id, 'Attribute 2' 
from my_table where id not in (
    select id 
    from my_table 
    where attribute in ('Attribute 1', 'Attribute 2')
    group by id 
    having count(*) = 2
    ) 
where Attribute = 'Attribute 1'