I’m looking to use a LEFT JOIN query to acquire some results from two tables with a one-to-many relationship, but limit the result set based on the count of “children”. I have two tables structured like:
customers
id name ...
1 "bob" ...
2 "jill" ...
orders
id customer_id ...
100 1 ...
101 2 ...
102 1 ...
(The rest of the data in the tables is irrelevant for this query.)
What I’d like to do is acquire all customer IDs and their order IDs, sorted by customer, but limited to customers that have placed more than one order. In this example, the results would look like:
cust_id order_id
1 100
1 102
I’ve started with a basic LEFT JOIN to pair order IDs with their customer, but can’t figure out how to leave out all customers that haven’t ordered at least twice.
SELECT
`customers`.`id` AS `cust_id`,
`orders`.`id` AS `order_id`
FROM
`customers`
LEFT JOIN `orders` ON
`customers`.`id` = `orders`.`customer_id`
ORDER BY
`cust_id`
Thanks all.
One way is to create an inline view that gets the customers that have more than one order and the inner join to it. You could also do an IN or EXISTS if you don’t like the JOIN