首页 > 解决方案 > 编写此 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

标签: mysqlsql

解决方案


考虑到 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

推荐阅读