2013-03-08 64 views
1

我有以下MySQL表MySQL的選擇statment

OrderId OrderItemId IsReceived 
    1   21   0 
    1   22   1 
    2   31   1 
    2   11   0 
    2   21   0 
    3   31   1 
    3   12   1 
  • 如果IsReceived == 1,表示這個項目被接收。

  • 如果IsReceived == 0,表示此項目尚未收到。

我想知道哪些訂單已被完全接收(所有orderItems接收),什麼是MySQL查詢?

在這種情況下,它會返回一個OrderId:3(因爲在orderId 3,收到的所有訂單項)

回答

7

這裏有一個解決方案:

SELECT OrderId 
FROM `IHaveFollowingMySQLTable` 
GROUP BY OrderID 
HAVING MIN(IsReceived) = 1 
0

而另一

SELECT OrderId 
    FROM OrderItems 
GROUP BY OrderID 
HAVING SUM(IsReceived) = COUNT(IsReceived) 

但@Bill Karwin的答案是最優雅的。

0
select distinct(tbl.OrderId) from your_table_name tbl where tbl.OrderId not in 
(select distinct(tbl2.OrderId) from your_table_name tbl2 where tbl2.IsReceived=0)