嵌套的SQL语句(简单)

时间:2016-02-18 17:40:10

标签: sql postgresql

我正在尝试运行一个查询来获取订购产品p01和p07的客户(cid)的ID。

这是我的工作方式,但它什么都不返回:

SELECT cid
FROM customers
WHERE cid IN (SELECT cid
              FROM orders
              WHERE pid IN (SELECT pid
                            FROM products
                            WHERE pid = 'p01'
                            AND pid = 'p07'));

2 个答案:

答案 0 :(得分:0)

您的原始查询不会返回任何行,因为

 SELECT pid 
 FROM products
 WHERE pid = 'p01' AND pid = 'p07';

永远不会返回任何行,因为永远不会满足条件WHERE pid = 'p01' AND pid = 'p07'

你应该做的是:

SELECT cid
FROM customers
WHERE cid IN (SELECT cid
              FROM orders
              WHERE pid IN (SELECT pid
                            FROM products
                            WHERE pid IN ('p01', 'p07')));

您也可以使用JOIN:

SELECT DISTINCT C.cid
FROM   customers AS C 
       INNER JOIN 
       orders AS O ON O.cid = C.cid
       INNER JOIN 
       products AS P ON P.pid = O.pid
WHERE   P.pid IN ('p01', 'p07')

如果您不想使用DISTINCT,那么您可以这样做:

SELECT  C.cid
FROM    customers AS C 
WHERE   EXISTS  (SELECT O.cid 
              FROM   orders AS O INNER JOIN 
                     products AS P ON P.pid = O.pid
              WHERE  P.pid IN ('p01', 'p07') AND O.cid = C.cid)

根据你的评论“它返回c001,c004和c006,但是客户c004只订购了其中一个产品(p01)而不是两者(p07和p01)”我认为你需要这样做:

SELECT  C.cid
FROM    customers AS C 
WHERE   EXISTS  (SELECT O.cid 
              FROM   orders AS O INNER JOIN 
                     products AS P ON P.pid = O.pid
              WHERE  P.pid IN ('p07') AND O.cid = C.cid) AND 
        EXISTS (SELECT O.cid 
              FROM   orders AS O INNER JOIN 
                     products AS P ON P.pid = O.pid
              WHERE  P.pid IN ('p01')  AND O.cid = C.cid ) 

答案 1 :(得分:0)

pid绝不是'p01' 'p07'。使用OR,或仅使用IN

SELECT DISTINCT customers.cid
FROM customers
JOIN orders ON orders.cid = customers.cid
WHERE orders.pid IN ('p01', 'p07')