从删除查询中排除特定记录

时间:2013-02-20 19:46:23

标签: mysql

假设我有一些这样的数据(日期类型的东西,月/日/年/标志/用户列)

1 - 1 - 2013 flag:1 user:123456
1 - 2 - 2013 flag:0 user:123456
1 - 3 - 2013 flag:0 user:123456
1 - 4 - 2013 flag:0 user:123456
1 - 5 - 2013 flag:1 user:123456
3 - 1 - 2013 flag:1 user:987654
3 - 2 - 2013 flag:0 user:987654
3 - 3 - 2013 flag:0 user:987654
3 - 4 - 2013 flag:0 user:987654
3 - 5 - 2013 flag:1 user:987654

我想删除用户123456中除第一个以外的所有记录。我试过了:

DELETE FROM table 
WHERE year = 2013 
AND user = 123456 
AND (month != 1 AND day != 1 AND year != 2013 AND flag != 1)

旗帜很重要。我很难过。我试过不喜欢这样:

DELETE 
FROM table 
WHERE year = 2013 
AND user = 123456 
NOT IN (SELECT * 
        FROM table 
        WHERE month = 1 AND day = 1 AND year = 2013 AND flag = 1)

但我不能不工作。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的第一个查询失败,因为无法year = 2013year != 2013。试试下面的修改版本。

DELETE FROM table 
WHERE year = 2013 
AND user = 123456 
AND NOT (month = 1 AND day = 1 AND year = 2013 AND flag = 1)