--使用in查找订购物品(prod_id)为RGAN01的顾客信息
SELECT CUST_NAME, CUST_CONTACT
FROM CUSTOMERS
WHERE CUST_ID IN
(SELECT CUST_ID
FROM ORDERS
WHERE ORDER_NUM IN
(SELECT ORDER_NUM FROM ORDERITEMS WHERE PROD_ID = 'RGAN01'));
以下为查询结果:
-使用exists查找订购物品为RGAN01d的顾客信息
SELECT CUST_NAME, CUST_CONTACT
FROM CUSTOMERS
WHERE EXISTS
(SELECT CUST_ID
FROM ORDERS
WHERE EXISTS
(SELECT ORDER_NUM FROM ORDERITEMS WHERE PROD_ID = 'RGAN01'));
以下为查询结果:
请教为何两次结果不同?使用in和exists的差别是啥?
4 个解决方案
#1
加上ORDERS表和ORDERITEMS表字段相等的条件
#2
SELECT CUST_NAME, CUST_CONTACT
FROM CUSTOMERS a
WHERE EXISTS
(SELECT *
FROM ORDERS b
WHERE a.CUST_ID=c.CUST_ID and EXISTS
(SELECT * FROM ORDERITEMS c WHERE PROD_ID = 'RGAN01' and b.ORDER_NUM=c.ORDER_NUM )
);
这样执行一下,结果应该是一样的
FROM CUSTOMERS a
WHERE EXISTS
(SELECT *
FROM ORDERS b
WHERE a.CUST_ID=c.CUST_ID and EXISTS
(SELECT * FROM ORDERITEMS c WHERE PROD_ID = 'RGAN01' and b.ORDER_NUM=c.ORDER_NUM )
);
这样执行一下,结果应该是一样的
#3
嗯,谢谢,忘加条件了,还有顺便说下,你写的第一个where子句里的条件应该是a.CUST_ID=b.CUST_ID
#4
你首先要知道in和exists有什么区别,一个in是可以返回值,而exists却只是告诉你它在不在而已
#1
加上ORDERS表和ORDERITEMS表字段相等的条件
#2
SELECT CUST_NAME, CUST_CONTACT
FROM CUSTOMERS a
WHERE EXISTS
(SELECT *
FROM ORDERS b
WHERE a.CUST_ID=c.CUST_ID and EXISTS
(SELECT * FROM ORDERITEMS c WHERE PROD_ID = 'RGAN01' and b.ORDER_NUM=c.ORDER_NUM )
);
这样执行一下,结果应该是一样的
FROM CUSTOMERS a
WHERE EXISTS
(SELECT *
FROM ORDERS b
WHERE a.CUST_ID=c.CUST_ID and EXISTS
(SELECT * FROM ORDERITEMS c WHERE PROD_ID = 'RGAN01' and b.ORDER_NUM=c.ORDER_NUM )
);
这样执行一下,结果应该是一样的
#3
嗯,谢谢,忘加条件了,还有顺便说下,你写的第一个where子句里的条件应该是a.CUST_ID=b.CUST_ID
#4
你首先要知道in和exists有什么区别,一个in是可以返回值,而exists却只是告诉你它在不在而已