creating a query for customers that have only ordered once - mySQL
Hiya
My brain is struggling with this one - I need a MySQL query that pulls out the details for customers that have only ordered once - and as I would like to use query builder it would be great if it was in 1 query (hence my issue)
this seems to give me the details or number of orders per customer_id:
Code:
SELECT c.customers_id, COUNT(c.customers_id) as ccount FROM customers c, orders o WHERE c.customers_id=o.customers_id GROUP BY (c.customers_id)
but then I am trying to get it into a list of their details
Code:
SELECT c.customers_email_address, c.customers_lastname, c.customers_firstname from customers c
WHERE c.customers_id IN (SELECT c.customers_id, COUNT(c.customers_id) FROM customers c, orders o WHERE c.customers_id=o.customers_id GROUP BY (c.customers_id)) GROUP BY
c.customers_email_address ORDER BY c.customers_lastname, c.customers_firstname ASC
but also need to have the COUNT = 1
failing miserably!
I can do it in different steps offline but is it possible to do online via query_builder and online?
thank you
Sarah
Re: creating a query for customers that have only ordered once - mySQL
The following query (which returns all information for matching customer records) appears to do the trick:
Code:
SELECT c.*, oc.num_orders
FROM customers c
INNER JOIN
(SELECT customers_id, COUNT(customers_id) as num_orders
FROM orders
GROUP BY customers_id) AS oc
ON oc.customers_id = c.customers_id
WHERE oc.num_orders = 1
Re: creating a query for customers that have only ordered once - mySQL
THANK YOU! Much appreciated I always always forget about INNER JOIN! but been too long since I just did MySQL statement - much appreciated thank you