MySQL排除行子查询 [英] MySQL exclude rows subquery

查看:74
本文介绍了MySQL排除行子查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取所有行,但要避免"状态"列中具有"离开"条目的行。

我想知道"Trips"是否已"到达"为"Status",但排除那些已将"离开"列为"Status"的旅行。

我已尝试使用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

这里是SQL小提琴:http://sqlfiddle.com/#!9/9ec331/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

这篇关于MySQL排除行子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆