要跟踪订单,我需要订单表中的订单ID,并检查订单表,该订单是在特定日期范围内进行的。使用以下查询我可以获得id,但它也将返回id 3,这也是不需要的。
示例:请参阅orderdates表。 id 3的第一个日期与id 2的最后日期重叠。
如果ID的第一个日期与其他ID的最后日期重叠或甚至是否可能,我如何更改不返回ID的查询?
SELECT id
FROM orders
WHERE id in(
SELECT id
FROM orderdates
WHERE
orderdate BETWEEN '2017-06-01' AND '2017-06-30'
GROUP BY id);
orders
id sent
1 1
2 1
3 1
orderdates
id orderdate
1 2017-6-10
1 2017-6-11
1 2017-6-12
1 2017-6-13
2 2017-6-14
2 2017-6-15
2 2017-6-16
2 2017-6-17 <--- Last date of id 2
3 2017-6-17 <--- First date of id 3
3 2017-6-18
3 2017-6-19
3 2017-6-20
答案 0 :(得分:0)
也许我将每个id的最小日期与每个id的最大日期进行比较
select u.*
from t u
where u.id not in
(
select z.id
from
(
select s.*,t.id tid,t.mindt tmindt,t.maxdt tmaxdt
from
(
select id, min(dt) mindt,max(dt) maxdt
from t
group by id
order by id
) s
join
(select id, min(dt) mindt,max(dt) maxdt
from t
group by id
order by id
) t on
t.id <> s.id and
t.maxdt = s.mindt
) z
)
order by u.id,u.dt
鉴于此
truncate table t;
insert into t values
(1,'2017-01-01'),(1,'2017-01-02'),
(2,'2017-01-03'),(2,'2017-01-04'),
(3,'2017-01-04')
结果
+------+------------+
| id | dt |
+------+------------+
| 1 | 2017-01-01 |
| 1 | 2017-01-02 |
| 2 | 2017-01-03 |
| 2 | 2017-01-04 |
+------+------------+
4 rows in set (0.00 sec)
鉴于此
truncate table t;
insert into t values
(1,'2017-01-01'),(1,'2017-01-02'),
(2,'2017-01-03'),(2,'2017-01-04'),
(3,'2017-01-04'),
(4,'2017-01-04'),(4,'2017-01-06');
结果
+------+------------+
| id | dt |
+------+------------+
| 1 | 2017-01-01 |
| 1 | 2017-01-02 |
| 2 | 2017-01-03 |
| 2 | 2017-01-04 |
+------+------------+
4 rows in set (0.00 sec)
鉴于
truncate table t;
insert into t values
(1,'2017-01-01'),(1,'2017-01-02'),
(2,'2017-01-03'),(2,'2017-01-04'),
(3,'2017-01-04'),
(4,'2017-01-05'),(4,'2017-01-06');
结果
+------+------------+
| id | dt |
+------+------------+
| 1 | 2017-01-01 |
| 1 | 2017-01-02 |
| 2 | 2017-01-03 |
| 2 | 2017-01-04 |
| 4 | 2017-01-05 |
| 4 | 2017-01-06 |
+------+------------+
6 rows in set (0.02 sec)