sql双重 not exist 问题求教!!想了好久了

PKnotnull 2016-07-22 11:12:14
Agents表

customers表

products表

orders表



要求查询订购了所有产品顾客的cid值

下面是我写的代码,结果是对的,感觉过程有问题。
select c.cid from CUSTOMERS c
where not exists
(select * from products p
where not exists
(select * from orders o
where o.cid=c.CID and p.pid=o.pid))

我现在的问题是,如果取顾客c001,那么在执行最后一段代码o.cid=c.CID时,对于orders表中cid为c002的行,判定永远为false,那么这时候就有元素返回,第一个not exists 则判定为false,所以c001不成立。但是执行这段代码的结果是c001,这是为什么啊????想不明白
...全文
254 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
唐诗三百首 2016-07-22
  • 打赏
  • 举报
回复
引用 4 楼 PKnotnull 的回复:
谢谢你了,这个方法我知道,我是不明白为什么我的那个方法最后得出的结果竟然也正确
可能是巧合而已, 建议不要把简单的问题复杂化了, 其实不需要用到CUSTOMERS表.
PKnotnull 2016-07-22
  • 打赏
  • 举报
回复
引用 2 楼 ap0405140 的回复:

-- 要求查询订购了所有产品顾客的cid值
select cid
 from orders
 group by cid
 having count(distinct pid)=(select count(1) from products)
谢谢你了,这个方法我知道,我是不明白为什么我的那个方法最后得出的结果竟然也正确
快溜 2016-07-22
  • 打赏
  • 举报
回复
写这个麻烦,自己把自己都套进去了 c001时,里层数据全fasle,外层当然是true
唐诗三百首 2016-07-22
  • 打赏
  • 举报
回复

-- 要求查询订购了所有产品顾客的cid值
select cid
 from orders
 group by cid
 having count(distinct pid)=(select count(1) from products)
kingtiy 2016-07-22
  • 打赏
  • 举报
回复

select  c.cid
from    CUSTOMERS c
where   not exists ( select *
                     from   products p
                     where  not exists ( select *
                                         from   orders o
                                         where  p.pid=o.pid )
                            and o.cid=c.CID );--这个条件拿到外层,感觉逻辑更清晰一些.

PKnotnull 2016-07-22
  • 打赏
  • 举报
回复
哎,果然是自己懵逼了,我的那种方法是对的,不过想的想的又绕进去了。现在明白了。我好蠢啊!!!!!!

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧