1

这是一个示例查询:

SELECT customerName from customers 
WHERE customerNUMBER IN 
( SELECT customerNumber FROM orders 
  WHERE orderNumber 
    IN ( SELECT orderNumber FROM orderdetails 
    INNER JOIN products on orderdetails.productCode = products.productCode 
    where products.buyPrice > 100 ));

我相信这些表格是不言自明的。

有一个更好的方法吗?

SQL菜鸟在这里。

4

3 回答 3

13

我的建议是将其更改为JOIN语法,而不是所有 WHERE/IN 子句过滤:

select c.customerName
from customer c
inner join orders o
  on c.customerNumber = o.customerNumber
inner join orderdetails od
  on o.orderNumber = od.orderNumber
inner join products p
  on od.productCode = p.productCode
where p.buyPrice > 100;

如果需要,如果有重复项,您可能必须向查询添加 DISTINCT。

于 2013-05-01T16:31:22.600 回答
8

在整个过程中使用正常的内部连接,如果需要消除重复,则在 group by 或 distinct 子句中折腾:

select customers.*
from customers
join orders on ...
join orderdetails on ...
join products on ...
group by customers.customerNumber
于 2013-05-01T16:30:50.750 回答
2

EXISTS允许您组合所有子查询部分。重复不是问题:

  • customers从外部查询中只能看到表
  • EXISTS为每一customers行产生一个布尔结果:

--

SELECT customerName from customers cc
WHERE EXISTS (
        SELECT * 
        FROM orders oo
        JOIN orderdetails od ON od.orderNumber = oo.orderNumber
        JOIN products pr ON od.productCode = pr.productCode
        WHERE oo.customerNUMBER = cc.customerNumber
        AND pr.buyPrice > 100 
        );
于 2013-05-01T17:11:03.407 回答