Eric Milford :: Web Developer & Food Advocate

SQL: Introducing Having

Posted by Eric Milford on May 07, 2010

Tagged with ruby on rails, technology

I was asked recently to write the SQL needed to define a class method named User.busy? that would return an array of User records with a post count greater than or equal to 2.

Let's assume we have two tables, users and posts, linked by the primary key users.id and the foreign key posts.user_id.

I knew high level that I would need a join between the two tables and some way to apply a where clause on the count of posts grouped by users. A quick bit of research introduced me to the group by plus having technique.

1 select users.* from users join posts on posts.user_id = users.id group by posts.user_id having count(*) >= 2

Ta da!

Read Full Post »