如果其中一条记录具有某个order_status_id,mysql将删除所有记录

时间:2016-12-07 04:38:37

标签: mysql

这是一个表结构:

order_id | order_status_id |      ip     | date_added
-----------------------------------------------     
1        | 0               | 192.168.1.1 | 2016-12-07
2        | 0               | 192.168.1.1 | 2016-12-07
3        | 0               | 192.168.1.1 | 2016-12-07
4        | 0               | 192.168.1.1 | 2016-12-07
5        | 1               | 192.168.1.1 | 2016-12-07

我有一个sql请求,删除id值最低的行,在我的情况下,我们删除order_id = 1,2,3的记录

    delete n1 FROM `order` n1, `order` n2 
    WHERE n1.order_id > n2.order_id 
    AND n1.order_status_id = '0' 
    AND n2.order_status_id = '0' 
    AND n1.ip = n2.ip
    AND Day(n1.date_added) = Day(n2.date_added)

但我想用order_status_id = 0(1,2,3,4)删除所有记录,如果其中一条记录(来自同一个ip / date_added)的order_status_id = 1(在我的情况下因为我们有记录order_id 5 with order_status_id = 1)。

2 个答案:

答案 0 :(得分:0)

您可以使用join

delete o
    from orders o join
         (select ip, date_added
          from orders o
          where order_status_id = 1
          group by ip, date_added
         ) oo
         on o.ip = oo.ip and o.date_added = oo.date_added
    where o.order_status_id = 0;

答案 1 :(得分:0)

实际上,仍然不知道你真正想做什么,但试试这个:

DELETE n1 FROM `order` n1
JOIN (
    SELECT
        MAX(`order_id`) AS `order_id`
    FROM `order` o1
    WHERE
    (NOT EXISTS(SELECT 1 FROM `order` o2 WHERE o1.`ip` = o2.`ip` AND o1.`date_added` = o2.`date_added` AND o2.`order_status_id` = '1')
     AND o1.`order_status_id` = '0')
    OR
    (EXISTS(SELECT 1 FROM `order` o2 WHERE o1.`ip` = o2.`ip` AND o1.`date_added` = o2.`date_added` AND o2.`order_status_id` = '1')
      AND o1.`order_status_id` = '1')
    GROUP BY `ip`, `date_added`
) n2
ON n1.`order_id` <> n2.`order_id`

SqlFiddle demo