How to use not exists in a sql query with w3schools?

。_饼干妹妹 提交于 2019-12-11 05:17:36

问题


I have an issue with not exists sql query at w3schools

I want to select all customers that work with shipperid = 1 BUT not shipperid = 3. I tried the following:

select o1.customerid, o1.shipperid
from orders o1
where o1.shipperid=1 and not exists
(select o2.customerid from orders o2
where o1.orderid=o2.orderid
and o2.shipperid=3)
order by customerid
;

The above query gives all customers that work with shipperid = 1 and does NOT exclude customers who work with shipperid = 3. What is not correct with the query. (I need to speifically use not exists)


PS: I know the in solution:

select customerid, shipperid
from orders
where shipperid=1 and customerid not in (
select customerid
from orders
where shipperid=3
)
order by customerid;

Why does not the not exists solution work?


回答1:


I'm fairly certain that the problem lies in the way you're joining the correlated subquery, on orderid = orderid. I'm not familiar with this dataset, but it seems surprising that the same order would have different shippers, and it adds a condition not found in your 'correct' answer. This should work:

select o1.customerid
      ,o1.shipperid
from orders as o1
where o1.shipperid = 1 
and not exists (
    select o2.orderid 
    from orders as o2
    where o1.customerid = o2.customerid
    and o2.shipperid = 3)
order by customerid
;


来源:https://stackoverflow.com/questions/18197366/how-to-use-not-exists-in-a-sql-query-with-w3schools

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!