预订系统会删除一段时间内所有已保存的预订

时间:2019-05-27 12:43:06

标签: mysql sql

我有多个预订处于待处理状态。但是其中之一已付款,现在状态已确认。

这是我所拥有的一个例子:

id |       start_date       |        end_date       |  status
   |                        |                       |
1  |   2019-06-10 08:00:00  |  2019-06-10 20:00:00  |  pending    <-- To delete
2  |   2019-06-10 10:00:00  |  2019-06-10 13:00:00  |  confirmed
3  |   2019-06-09 06:00:00  |  2019-06-11 11:00:00  |  pending    <-- To delete
4  |   2019-06-10 21:00:00  |  2019-06-10 22:00:00  |  pending    <-- Keep it
5  |   2019-06-10 11:00:00  |  2019-06-10 12:00:00  |  pending    <-- To delete

ID 2已确认,我需要删除所有处于确认状态的处于待处理状态的预订。

所以我需要删除ID 1、3和5

如何使用SQL查询做到这一点?

我考虑过,但不确定是否可以涵盖所有可能的情况:

DELETE FROM booking 
WHERE status = 'pending' 
AND start_date <= '2019-06-10 10:00:00' 
AND end_date >= '2019-06-10 13:00:00'

2 个答案:

答案 0 :(得分:2)

我认为您想要重叠的间隔。这将是:

DELETE b
    FROM booking b
    WHERE b.status = 'pending' AND
          b.end_date >= '2019-06-10 10:00:00' AND
          b.start_date <= '2019-06-10 13:00:00';

如果第二个在第一个开始时或之后结束,并且第二个在第一个结束时或之前结束,则两个间隔重叠。

答案 1 :(得分:1)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,start_date DATETIME NOT NULL
,end_date DATETIME NOT NULL
,status VARCHAR(12) NOT NULL
);

INSERT INTO my_table VALUES
(1,'2019-06-10 08:00:00','2019-06-10 20:00:00','pending'),
(2,'2019-06-10 10:00:00','2019-06-10 13:00:00','confirmed'),
(3,'2019-06-09 06:00:00','2019-06-11 11:00:00','pending'),
(4,'2019-06-10 21:00:00','2019-06-10 22:00:00','pending'),
(5,'2019-06-10 11:00:00','2019-06-10 12:00:00','pending');

DELETE y 
  FROM my_table x 
  JOIN my_table y 
    ON y.start_date <= x.end_date 
   AND y.end_date > x.start_date 
 WHERE x.status = 'confirmed' 
   AND y.id <> x.id;

Query OK, 3 rows affected (0.00 sec)

SELECT * FROM my_table;
+----+---------------------+---------------------+-----------+
| id | start_date          | end_date            | status    |
+----+---------------------+---------------------+-----------+
|  2 | 2019-06-10 10:00:00 | 2019-06-10 13:00:00 | confirmed |
|  4 | 2019-06-10 21:00:00 | 2019-06-10 22:00:00 | pending   |
+----+---------------------+---------------------+-----------+
2 rows in set (0.00 sec)