加入收藏 | 设为首页 | 会员中心 | 我要投稿 大庆站长网 (https://www.0459zz.com/)- 科技、智能边缘云、事件网格、云计算、站长网!
当前位置: 首页 > 数据库 > MySql > 正文

mysql – 如何用JOIN替换NOT EXISTS?

发布时间:2021-01-11 08:46:52 所属栏目:MySql 来源:互联网
导读:我有以下查询:select distinct a.id, a.name from Employee a join Dependencies b on a.id = b.eid where not exists ( select * from Dependencies d where b.id = d.id and d

我有以下查询:

select distinct a.id,a.name
from Employee a
join Dependencies b on a.id = b.eid
where not exists 
    ( 
select * 
    from Dependencies d 
    where b.id = d.id 
    and d.name  = 'Apple'
    )
and exists 
    (
    select * 
    from Dependencies c 
    where b.id = c.id 
    and c.name  = 'Orange'
    );

我有两张桌子,比较简单.
第一个Employee有一个id列和一个name列
第二个表Dependencies有3列,一个id,一个eid(要链接的员工ID)和名称(apple,orange等).

数据看起来像这样
Employee表看起来像这样

id  | name
-----------
1   | Pat
2   | Tom
3   | Rob
4   | Sam

依赖

id  | eid | Name
--------------------
1   | 1   |  Orange
2   | 1   |  Apple
3   | 2   |  Strawberry
4   | 2   |  Apple
5   | 3   |  Orange
6   | 3   |  Banana

正如你所看到的,帕特同时拥有Orange和Apple,他需要被排除在外,它必须是通过连接,我似乎无法让它工作.最终数据应该只返回Rob 最佳答案 使用您想要的名称进行内连接,在您不使用的名称上左连接,然后使用where确保左连接无法匹配,如此(SQL Fiddle):

select distinct a.id,a.name
from Employee a
  inner join Dependencies b on a.id = b.eid
    and b.name = 'Orange'
  left join Dependencies c on ( a.id = c.eid
    and c.name = 'Apple')
where c.id is null;

(编辑:大庆站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读