我有2张表:
命令:
Id | Status -----+-------- 1 | OK 2 | WAITING 3 | WAITING 4 | OK 5 | OK 6 | OK
和Order_details:
Id | Order_Id | Status -----+------------+-------- 1 | 1 | S1 2 | 1 | S1 3 | 2 | S1 4 | 4 | S2 5 | 4 | S2 6 | 4 | S3 7 | 5 | S1 8 | 5 | S1
我需要做的是选择所有具有多个Order_detail的订单,并且订单状态必须为“ OK”,并且每个order_detail的状态都 必须 为(S1,S2)
我做了这样的事情:
SELECT O.Id FROM Orders O JOIN Order_details OD ON O.Id=OD.Order_Id WHERE O.Status='OK' AND OD.Status IN ('S1','S2') GROUP BY O.Id HAVING count(DISTINCT OD.Id)>1
但这将返回所有具有多个Order_details满足条件的订单。
我确定这部分很好:
SELECT O.Id FROM Orders O JOIN Order_details OD ON O.Id=OD.Order_Id WHERE O.Status='OK' GROUP BY O.Id HAVING count(DISTINCT OD.Id)>1
但是我必须检查以上订单的每个Order_detail是否都具有状态IN(S1,S2)。
因此,如果“订单”有2个详细信息,其中一个状态为“ S1”,第二个“ S3”,则应跳过此订单。
SELECT O.Id FROM Orders O JOIN Order_details OD ON O.Id=OD.Order_Id WHERE O.Status=’OK’ GROUP BY O.Id HAVING count(DISTINCT OD.Id)>1 AND SUM(CASE WHEN OD.Status NOT IN (‘S1’,’S2’) THEN 1 ELSE 0 END) = 0