0

I currently have this query.

SELECT DISTINCT (o.customer_id), count( o.id ) AS orders, c.* 
FROM `order` AS o LEFT JOIN customer AS c ON o.customer_id = c.id 
GROUP BY customer_id

What it does is it returns all customers that have made an order and counts the number of orders each customer has made.

What I need to do is modify this query so it also returns those customers who haven't made an order. Do you have any idea how this would be done?

I tried to reverse the query but this didn't do the trick..

SELECT DISTINCT (o.customer_id), count( o.id ) AS orders, c.* 
FROM customer AS c LEFT JOIN order AS o ON o.customer_id = c.id 
GROUP BY o.customer_id
2
  • u already write DISTINCT (o.customer_id) then what is the need of GROUP BY customer_id Commented Apr 7, 2011 at 9:41
  • the distinct does nothing in this case .. Commented Apr 7, 2011 at 9:43

3 Answers 3

1

Try this.

SELECT o.customer_id, sum( case when o.id is not null then 1 else 0 end ) AS orders, c.* 
FROM customer  c
LEFT JOIN order o ON o.customer_id = c.id GROUP BY customer_id
Sign up to request clarification or add additional context in comments.

Comments

1

What about:

SELECT DISTINCT (o.customer_id), count( o.id ) AS orders, c.* 
    FROM `order` AS o 
    LEFT OUTER JOIN customer AS c ON o.customer_id = c.id GROUP BY customer_id

Comments

0
SELECT o.customer_id, c.* 
FROM customer AS c LEFT JOIN order AS o ON o.customer_id = c.id 
WHERE o.id IS NULL
GROUP BY o.customer_id

You can also skip the "GROUP BY" clause because when the orders side is NULL, there is always only one row for the customer:

SELECT o.customer_id, c.* 
FROM customer AS c LEFT JOIN order AS o ON o.customer_id = c.id 
WHERE o.id IS NULL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.