hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Friday

2005.04.29

Any? and All? for MySQL #

by why in inspect

Seisyll Wyn sends in a tidy MySQL hack:

 SELECT COUNT(*) AS total_students, 
        MAX(student_id = 130220) AS signed_up
 FROM class_signups WHERE class_id = 1347

Can you tell what this does? The MAX aggregate function coupled with the comparison acts like Ruby’s Enumerable#any? Great if you’re retrieving a count and simultaneously want to ask, “Is the current user in that count?”

Similarly, the MIN aggregate function can be leveraged for Enumerable#all?.

 SELECT COUNT(*) AS total_students, 
        MIN(status = 'ACTIVE') AS all_active
 FROM class_signups WHERE class_id = 1347

Not having poked in the MySQL function book for a little while, maybe there are other ways to do this?