SQL获取仅包含一种物料的所有订单

时间:2018-11-22 12:12:06

标签: mysql sql database join

In this Database我想计算仅包含特定类别产品的订单数量。

我知道如何计算也包含某个类别(即类别1)项目的所有订单。

SELECT Count(DISTINCT orderdetails.orderid) AS "AllCat1" 
FROM   orderdetails 
       INNER JOIN orders 
               ON orderdetails.orderid = orders.orderid 
                  AND orderdetails.productid IN (SELECT DISTINCT productid 
                                                 FROM   products 
                                                 WHERE  categoryid = 1) 
WHERE  orderdate BETWEEN "1996-12-01" AND "1996-12-31"; 

我很难找到一种优雅的方式来获取仅包含类别1物料的所有订单。我尝试选择所有OrderID并按OrderID和CategoryID将它们分组:

SELECT * 
FROM   orderdetails 
       INNER JOIN orders 
               ON orderdetails.orderid = orders.orderid 
                  AND orderdate BETWEEN "1996-12-01" AND "1996-12-31" 
       INNER JOIN products 
               ON orderdetails.productid = products.productid 
GROUP  BY orderdetails.orderid, 
          categoryid;

但是我不知道如何计算仅包含类别1项目的所有OrderID。我的方法正确吗?还是有更好的方法(我确定有)

2 个答案:

答案 0 :(得分:2)

您可以使用group byhaving。 。 。但您需要两个级别。通过执行以下操作以获取全部(或一组类别)的订单:

SELECT o.orderId 
FROM orders o JOIN
     orderdetails od
     ON od.orderid = o.orderid JOIN
     products p
     ON p.productid = od.productid
WHERE o.orderdate BETWEEN '1996-12-01' AND '1996-12-31'
GROUP BY o.orderId
HAVING SUM(CASE WHEN p.categoryid IN (1) THEN 1 ELSE 0 END) = COUNT(*);

该计数需要一个子查询:

SELECT COUNT(*)
FROM (SELECT o.orderId 
      FROM orders o JOIN
           orderdetails od
           ON od.orderid = o.orderid JOIN
           products p
           ON p.productid = od.productid
      WHERE o.orderdate BETWEEN '1996-12-01' AND '1996-12-31'
      GROUP BY o.orderId
      HAVING SUM(CASE WHEN p.categoryid IN (1) THEN 1 ELSE 0 END) = COUNT(*)
     ) o;

答案 1 :(得分:1)

您可以使用HAVING子句进行过滤。我们基本上对订单类别为1的订单明细行进行计数。它应等于该顺序的总行数。这样可以确保订单中的所有类别均为1。

SELECT od.orderid 
FROM   orderdetails AS od 
       INNER JOIN orders AS o
               ON od.orderid = o.orderid 
                  AND o.orderdate BETWEEN "1996-12-01" AND "1996-12-31" 
       INNER JOIN products AS p
               ON od.productid = p.productid 
GROUP  BY od.orderid 
HAVING COUNT(CASE WHEN p.categoryid = 1 THEN 1 END) = COUNT(*)

为了代码清晰和可读性,建议在多表查询的情况下使用Aliasing