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!

Comments (3)

  • Dad
    May 08, 2010
    4:41pm

    Ok...so you think you're all that! On a serious note, I am most pleased by the fact that you have posted your solution to share with others who may have the same challenge. Proud of you!.....Dad

     

  • Dad
    Aug 13, 2010
    1:57am

    Eric, Well, the weather continues to be hot and humid, yet your mother and I did our two mile walk together and shared some more quality time. Enjoyed having you down this past week. I'm still anticipating the lobster sandwich in NY....love Dad

     

  • 18607dc7098d879b13f5ed22a70c4302

    Eric
    Aug 13, 2010
    2:00am

    Looking forward to the cooler weather of Fall. It is blazing hot! I had two lobster rolls the other day that made me think of you. Always welcome to come up to NYC! Love you.

     

Leave a Comment

  •  (required)
  •  (required, will not be displayed)
  •  Please input the numeric day portion of today's date.