我正在嘗試選擇至少兩次使用相同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 | +------------+---------+-----------+
普通組在末尾添加另一個參加由規則,你可以編寫查詢作爲
說:「如果指定了一個GROUP BY子句,那麼SELECT列表中的每個列引用必須標識一個分組列或者是一個set函數的參數!」 (老年人MySQL不關心這一點,並返回一個任意結果。較新的MySQL更嚴格,並且不會執行無效查詢。) – jarlh