删除下面部分中定义的逻辑语句

时间:2015-08-02 22:12:50

标签: mysql sql sql-server

请帮助我为以下方案编写删除查询。见下表。如果该项目至少有一个itemIDFlag,我需要从表格中删除这些true。在下面的情况下,应删除项A53-30374,因为Flags中至少有一个是true

itemid    Flag
------------------
V0000001    0    
V0000001    0    
V0000001    0    
V0000001    0    
V0000001    0    
V0000001    0    
V0000001    0    
V0000001    0    
V0000001    0    
V0000001    0    
V0000001    0    
V0000001    0    
V0000002    1    
V0000002    0    
V0000002    0    
V0000002    0    
V0000002    0    
V0000002    0     
V0000002    0    
V0000002    0    
V0000002    0    
V0000002    0    
V0000002    0    
V0000002    0    

2 个答案:

答案 0 :(得分:1)

delete from your_table 
where itemid in 
(select itemid from your_table 
where RELEASETOAX_YN = 1);

答案 1 :(得分:0)

ANSI SQL的方法是:

delete from t
     where 1 = (select count(*)
                from t t2
                where t.itemId = t2.itemId and t2.flag = 1
               );

虽然是标准语法,但MySQL的版本略有不同。

注意:上面特别是关于使用flag = 1准确查找 1 行。如果您只想删除任何至少有一个flag = 1的id,那么更有效的方法是:

delete from t
     where exists (select 1
                   from t t2
                   where t.itemId = t2.itemId and t2.flag = 1
                  );