In MySQL, how can you select data where every row meets a certain condition? For example lets say I have a table showing when employees arrived at work, it has three fields:
CREATE TABLE ArrivalTimes (UserID INT ,Day DATE ,ArrivalTime TIME );
I want to select all UserIDs of employees who have never been late (arrived 9am or earlier), what’s the best way to do this?
The answers from @jjclarkson and @davethegr8 are close, but you can’t put aggregate functions in the WHERE clause. The WHERE clause is evaluated for each row.
You need to evaluate the
MAX()expression for each group, so you need to use aHAVINGclause.Try this:
@MBCook comments that
HAVINGcan be slow. You’re right, it might not be the absolute quickest way to produce the desired result. But theHAVINGsolution is the most clear. There are situations where performance has lower priority than clarity and maintainability.I looked at the EXPLAIN output (on MySQL 5.1.30) for the
HAVINGsolution: no indexes were used, and the extra notes said ‘Using temporary; Using filesort,’ which usually means performance will be poor.Consider the following query:
This generates an optimization plan that uses an index on
UserIDand says:Using index; Using temporary‘Using where; Distinct‘Finally, the following query generates an optimization plan that appears to use indexes most effectively, and no temp tables or filesort.
Using where; Using index‘Using where‘This appears most likely to have the best performance. Admittedly, I only have four rows in my test table, so this isn’t a representative test.