mysql - 编写此 SQL 查询的更好方法是什么?
问题描述
我写了一个这样的查询,
select Client_Id, Driver_Id
from Trips
where Client_Id not in (select Users_Id from Users where Banned = 'Yes')
and Driver_Id not in (select Users_Id from Users where Banned = 'Yes')
我尝试了以下方法,但这给了我一个错误。为什么?如果这是不可能的,那么编写此查询的更好方法是什么?
select Client_Id, Driver_Id
from Trips
where Client_Id not in (select Users_Id from Users where Banned = 'Yes') banned
and Driver_Id not in banned
解决方案
考虑到 User_ID 作为主键/唯一键,使用连接而不是 where 子句,根据我的个人经验,速度上的差异比使用 where 子句要大得多。因此,我的建议是编写用于相同目的的查询如下:-
select T.Client_Id, T.Driver_Id from Trips T
Left Join Users UC On T.Client_ID=UC.Users_ID and UC.Banned='Yes'
Left Join Users UD On T.Driver_ID=UD.Users_ID and UC.Banned='Yes'
where UC.User_ID Is Null and UD.User_ID Is Null
推荐阅读
- angular - 从 ts 文件访问 ag 网格
- c# - DynamoDB 的 C# API DescribeTableResponse 是否返回不正确的数据?
- istio - 使用 Istio 1.3 的服务之间的随机“上游连接错误或在标头之前断开/重置”
- java - 如何在 Selenium 中测试页面上的子链接
- r - 将多变量、多组数据转换为 ts 对象
- mysql - 如何从数据库中的文件夹中插入图像的名称(名称相同)
- javascript - 通过 Ajax/jQuery 在 Rails 中更新
- python - 如何使用 xlrd 打开 base64 解码的 excel 文件?
- sql - 基于值的选择语句中的多个条件
- reactjs - Yarn/NPM 链接包未在浏览器中显示更改