我正在尝试获取所有行,但要避免在“状态”列上输入“离开”行。
我想知道“旅行”已“到达”为“状态”,但排除了已经“离开”为“状态”的那些。
我已经尝试过GROUP BY DISTINCT
(没有理想的结果)。
数据表:
id trip type status date
1 1260 ocean arriving 2019-03-04
2 1260 ocean departing 2019-03-05
3 1261 ocean arriving 2019-03-05
4 1262 ocean arriving 2019-03-05
5 1263 ocean arriving 2019-03-08
6 1263 ocean departing 2019-03-09
查询:
SELECT * FROM `test` WHERE `status` NOT IN (select `status` FROM `test` WHERE `status` = 'departing')
Result:
id trip type status date
1 1260 ocean arriving 2019-03-04
3 1261 ocean arriving 2019-03-05
4 1262 ocean arriving 2019-03-05
5 1263 ocean arriving 2019-03-08
所需结果:
id trip type status date
3 1261 ocean arriving 2019-03-05
4 1262 ocean arriving 2019-03-05
答案 0 :(得分:3)
您可以使用not exists
来做到这一点:
select *
from test t
where status = 'arriving'
and not exists (select 1 from test
where trip = t.trip and status = 'departing')
我不确定您是否想要子查询的条件,例如:
where trip = t.trip and status = 'departing' and date > t.date
答案 1 :(得分:1)
您可以使用“日期”列并将值用作参数
SELECT * FROM test WHERE status <> 'departing' and date = '2019-03-05'
答案 2 :(得分:0)
您可以尝试此查询。它仅显示行号仅在1行中的行。
SELECT * FROM `test` WHERE `trip` IN (
select trip FROM `test` group by trip
having count(*) = 1
)
答案 3 :(得分:0)
在此示例中,我将结果分组在一个嵌套的where子句中。像这样:
SELECT * FROM test WHERE status = 'arriving' AND trip IN (SELECT trip FROM test GROUP BY trip HAVING count(trip) = 1);