I'm trying to select orders, which are send at least two times with the same addressId to a customer.
This is my table structure:
Customer Table:
+------------+-----------+ | customerId | addressId | +------------+-----------+ | 1 | 1 | | 2 | 2 | | 3 | 3 | | 4 | 4 | +------------+-----------+
Relation for Addresses to Orders
+---------+-----------+ | orderId | addressId | +---------+-----------+ | 1 | 1 | | 2 | 2 | | 3 | 2 | | 4 | 3 | | 5 | 4 | | 6 | 4 | +---------+-----------+
Order Table
+----+------------+-------+ | id | orderEntry | total | +----+------------+-------+ | 1 | timestamp | 4711 | | 2 | timestamp | 0815 | | 3 | timestamp | 1337 | +----+------------+-------+
Now I want a output like this:
+------------+---------+-----------+ | customerId | orderId | addressId | +------------+---------+-----------+ | 2 | 2 | 2 | | 2 | 3 | 2 | | 4 | 5 | 4 | | 4 | 6 | 4 | +------------+---------+-----------+
I've tried to get the right result with these Query, but I think I can't count the addresses this way.
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);
With these Query I only get a result like this:
+------------+---------+-----------+ | customerId | orderId | addressId | +------------+---------+-----------+ | 2 | 2 | 2 | | 4 | 5 | 4 | +------------+---------+-----------+