此查询未显示正确的结果。它显示了所有CustomerId。
select Customers.customerid, Customers.custfirstname, Customers.custlastname from customers
where exists (select * from customers c
inner join orders o on c.CUSTOMERID=o.CUSTOMERID
inner join ORDER_DETAILS od on o.ordernumber = od.ORDERNUMBER
inner join products on products.PRODUCTNUMBER= od.PRODUCTNUMBER
where products.CATEGORYID= 2 and o.customerid = o.customerid);
以上结果是
CUSTOMERID CUSTFIRSTNAME CUSTLASTNAME
---------- ------------------------- -------------------------
1001 Suzanne Viescas
1002 William Thompson
1003 Gary Hallmark
1004 Robert Brown
1005 Dean McCrae
1006 John Viescas
1007 Mariya Sergienko
1008 Neil Patterson
1009 Andrew Cencini
1010 Angel Kennedy
1011 Alaina Hallmark
1012 Liz Keyser
1013 Rachel Patterson
1014 Sam Abolrous
1015 Darren Gehring
1016 Jim Wilson
1017 Manuela Seidel
1018 David Smith
1019 Zachary Ehrlich
1020 Joyce Bonnicksen
1021 Estella Pundt
1022 Caleb Viescas
1023 Julia Schnebly
1024 Mark Rosales
1025 Maria Patterson
1026 Kirk DeGrasse
1027 Luke Patterson
1028 Jeffrey Tirekicker
28 rows selected
我对上述查询的含义相同;此查询显示正确的结果。 它显示了仅购买产品的客户的结果.CATEGORYID = 2
select distinct c.customerid, c.custfirstname, c.custlastname from customers c
inner join orders o on o.customerid=c.CUSTOMERID
inner join ORDER_DETAILS od on od.ORDERNUMBER=o.ORDERNUMBER
inner join products p on p.PRODUCTNUMBER=od.productnumber
where p.CATEGORYID= 2
order by 1;
正确的结果是
CUSTOMERID CUSTFIRSTNAME CUSTLASTNAME
---------- ------------------------- -------------------------
1002 William Thompson
1004 Robert Brown
1005 Dean McCrae
1006 John Viescas
1007 Mariya Sergienko
1008 Neil Patterson
1009 Andrew Cencini
1010 Angel Kennedy
1011 Alaina Hallmark
1012 Liz Keyser
1013 Rachel Patterson
1014 Sam Abolrous
1016 Jim Wilson
1017 Manuela Seidel
1018 David Smith
1019 Zachary Ehrlich
1020 Joyce Bonnicksen
1021 Estella Pundt
1023 Julia Schnebly
1024 Mark Rosales
1025 Maria Patterson
1026 Kirk DeGrasse
1027 Luke Patterson
23 rows selected
第一个查询中的问题是什么?
答案 0 :(得分:0)
正如JNevill所指出的,如果子查询中有任何结果,EXISTS
将返回true。如果您将其更改为:
SELECT c.customerid, c.custfirstname, c.custlastname
FROM customers AS c
WHERE c.customerid IN ( SELECT [subquery here...]
WHERE products.CATEGORYID = 2)
您的子查询不需要o.customerid = o.customerid
,因为这看起来像拼写错误,而不是o.customerid = c.customerid
,这在INNER JOIN
条件中有所涵盖。
****编辑[存在版本] ****
SELECT c1.customerid,
c1.custfirstname,
c1.custlastname
FROM customers AS c1
WHERE EXISTS ( SELECT 1
FROM customers c2
INNER JOIN orders o ON c2.CUSTOMERID = o.CUSTOMERID
INNER JOIN ORDER_DETAILS od ON o.ordernumber = od.ORDERNUMBER
INNER JOIN products ON products.PRODUCTNUMBER = od.PRODUCTNUMBER
WHERE products.CATEGORYID = 2 AND c2.customerid = c.customerid )
最好的方法就是自己的子查询:
SELECT c.customerid,
c.custfirstname,
c.custlastname
FROM customers AS c
INNER JOIN orders o ON c.CUSTOMERID = o.CUSTOMERID
INNER JOIN ORDER_DETAILS od ON o.ordernumber = od.ORDERNUMBER
INNER JOIN products ON products.PRODUCTNUMBER = od.PRODUCTNUMBER
WHERE products.CATEGORYID = 2