troubleshooting Question

MySQL query, not able to get correct result with Where, Group by and having

Avatar of practitioner
practitionerFlag for Singapore asked on
PHPMySQL Server
27 Comments1 Solution183 ViewsLast Modified:
Hi,
A table stores order status at various stages,
Pending (1), when the order is placed,
Processing (2), when the packaging and shipping starts,
Delivered (3), when it reaches the customer.
etc.

Following shows with sample data how it is stored, first 3 records say that order #200 is Delivered on 17th March, Processing on 16th March, Pending on 15th March:
orders_status_history_id, orders_id, orders_status_id, date_added
409,                      200,       3,                2010-03-17
408,                      200,       2,                2010-03-16
407,                      200,       1,                2010-03-15
405,                      196,       2,                2010-03-15
404,                      196,       1,                2010-03-14
...
...
...
7,                        2,         3,                2009-08-04

I want to list all the orders where there is only one status which is Pending (1), this order should not have other status e.g. Processing (2) or Delivered (3)

So I wrote this query but I'm not sure how correct it is:

SELECT  `orders_id`
FROM  `orders_status_history`
GROUP BY  `orders_id`
HAVING COUNT(`orders_status_id`) = 1
ORDER BY `orders_id`

Regards
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 27 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 27 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros