MySQL exclude rows subquery(MySQL排除行子查询)
本文介绍了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排除行子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:MySQL排除行子查询
基础教程推荐
猜你喜欢
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 无法解决整理冲突 2021-01-01
