2016-08-18 28 views
1

我正在嘗試選擇至少兩次使用相同addressId發送給客戶的訂單。sql選擇具有多個地址的訂單

這是我的表結構:

客戶表:

 
+------------+-----------+ 
| customerId | addressId | 
+------------+-----------+ 
|   1 |   1 | 
|   2 |   2 | 
|   3 |   3 | 
|   4 |   4 | 
+------------+-----------+ 

關係的地址到訂單

 
+---------+-----------+ 
| orderId | addressId | 
+---------+-----------+ 
|  1 |   1 | 
|  2 |   2 | 
|  3 |   2 | 
|  4 |   3 | 
|  5 |   4 | 
|  6 |   4 | 
+---------+-----------+ 

順序表

 
+----+------------+-------+ 
| id | orderEntry | total | 
+----+------------+-------+ 
| 1 | timestamp | 4711 | 
| 2 | timestamp | 0815 | 
| 3 | timestamp | 1337 | 
+----+------------+-------+ 

現在我想一個輸出喜歡 這個:

 
+------------+---------+-----------+ 
| customerId | orderId | addressId | 
+------------+---------+-----------+ 
|   2 |  2 |   2 | 
|   2 |  3 |   2 | 
|   4 |  5 |   4 | 
|   4 |  6 |   4 | 
+------------+---------+-----------+ 

我試圖用這些查詢得到正確的結果,但我認爲我不能用這種方法計算地址。

SELECT C.`customerId`, AO.`orderId`, AO`addressId` 
FROM customer AS C 
    JOIN address_order AS AO ON AO.addressId = C.addressId 
    JOIN order AS O ON O.id = AO.orderId 
GROUP BY AO.`orderId` 
HAVING (COUNT(AO.`addressId`) > 1); 

有了這些查詢我只得到一個結果是這樣的:

 
+------------+---------+-----------+ 
| customerId | orderId | addressId | 
+------------+---------+-----------+ 
|   2 |  2 |   2 | 
|   4 |  5 |   4 | 
+------------+---------+-----------+ 
+0

普通組在末尾添加另一個參加由規則,你可以編寫查詢作爲

select c.customerId, ao.orderId, ao.addressId from customer c join address_order ao on ao.addressId = c.addressId join ( select addressId, count(*) as tot from address_order group by addressId having tot = 2 )x on x.addressId = ao.addressId 

說:「如果指定了一個GROUP BY子句,那麼SELECT列表中的每個列引用必須標識一個分組列或者是一個set函數的參數!」 (老年人MySQL不關心這一點,並返回一個任意結果。較新的MySQL更嚴格,並且不會執行無效查詢。) – jarlh

回答

0

我沒有看到order表的使用在這裏。但是,如果要確保訂單表數據和address_order應具有數據,則可以使用order表。如果你想確保所有從customer_orderorderId都在order表,那麼你可以爲

join `order` o on o.id = ao.orderId 
+0

歡呼的隊友,你救了我的一天 –

0

試試這個

SELECT customerId FROM customer INNER JOIN (SELECT * FROM address_order GROUP BY addressId 
HAVING (COUNT(addressId) > 1)) AS t1 ON customer.addressId=t1.addressId