mysql - 如何删除条件记录

时间:2016-12-08 18:48:30

标签: mysql

这是我的表结构:

CREATE TABLE `order`
    (`order_id` int, `order_status_id` int, `ip` varchar(11), `date_added` datetime)
;

INSERT INTO `order`
    (`order_id`, `order_status_id`, `ip`, `date_added`)
VALUES
    (1, 0, '192.168.1.1', '2016-12-07 00:00:00'),
    (2, 0, '192.168.1.1', '2016-12-07 00:00:00'),
    (3, 0, '192.168.1.1', '2016-12-07 00:00:00'),
    (4, 0, '192.168.1.1', '2016-12-07 00:00:00'),
    (5, 1, '192.168.1.1', '2016-12-07 00:00:00'),

    (6, 0, '192.168.1.2', '2016-12-08 00:00:00'),
    (7, 0, '192.168.1.2', '2016-12-08 00:00:00'),
    (8, 0, '192.168.1.2', '2016-12-08 00:00:00'),
    (9, 0, '192.168.1.2', '2016-12-08 00:00:00'),
    (10, 1, '192.168.1.2', '2016-12-08 00:00:00'),

    (11, 0, '192.168.1.3', '2016-12-09 00:00:00'),
    (12, 0, '192.168.1.3', '2016-12-09 00:00:00'),
    (13, 0, '192.168.1.3', '2016-12-09 00:00:00'),
    (14, 0, '192.168.1.3', '2016-12-09 00:00:00'),
    (15, 0, '192.168.1.3', '2016-12-09 00:00:00');

http://sqlfiddle.com/#!9/20c0f

我希望sql擦除所有记录,除了order_id为5,10,15

的记录

解释:我想删除条件为order_status_id = 0的记录:

a)如果其中一条记录(来自同一个ip / date_added order_id)的order_status_id = 1,则删除所有order_status_id = 0的记录(来自同一个ip / date_added)。在我的示例中,应删除记录1-4和6-9。

b)如果没有来自同一ip / date_added的记录,order_id = 1(所有记录的order_status_id = 0),则留下一条记录,其中order_id最高(所有其他记录都被删除)。在我的示例中,应删除记录11-14。

1 个答案:

答案 0 :(得分:1)

<强> SQL DEMO

首先,你需要分开你的病情。您{ip,date}order_status_id {0,1}

-- first filter SELECT `ip`, `date_added` FROM `order` GROUP BY `ip`, `date_added` HAVING MAX(`order_status_id`) = 1; -- second filter SELECT `ip`, `date_added` FROM `order` GROUP BY `ip`, `date_added` HAVING MAX(`order_status_id`) = 0;
order_status_id = 0

首先删除 您删除了与第一个过滤条件匹配的所有人,但只删除了1的所有人,这意味着您留下了DELETE o FROM `order` o INNER JOIN ( SELECT `ip`, `date_added` FROM `order` GROUP BY `ip`, `date_added` HAVING MAX(`order_status_id`) = 1 ) filter ON o.`ip` = filter.`ip` AND o.`date_added` = filter.`date_added` WHERE o.`order_status_id` = 0;

DELETE o1
FROM `order` o1
INNER JOIN (
    SELECT `ip`, `date_added`
    FROM `order`
    GROUP BY `ip`, `date_added`
    HAVING MAX(`order_status_id`) = 0
) filter
  ON o1.`ip` = filter.`ip`
 AND o1.`date_added` = filter.`date_added`
LEFT JOIN `order` o2
  ON o1.`order_id` < o2.`order_id`
WHERE o2.`ip` IS NOT NULL;

第二次删除 你删除了匹配第二个过滤器的所有人,但留下没有任何id高于他的人。

{{1}}

<强>输出 enter image description here