1

I have two models:

  1. Product
  2. Click

I would like to get all products that have more than x clicks.

The tables looks like this:

Products

id 

,

Clicks

id | product_id

In ruby, the code might look like products.select {|p| p.clicks.size > x}. How might one write a similar query for mysql?

Thanks!

2
  • Are you just asking how to write SQL to perform this query? Or are you asking how to do it in ActiveRecord/Rails land? Commented Jan 28, 2013 at 23:54
  • In the end, I'll be writing it in Rails ARel. So that would be ideal. Commented Jan 29, 2013 at 17:45

2 Answers 2

1

To do this efficiently, you may want to look into using a counter cache. ActiveRecord has built in support for this concept, and it will keep you from having to do a subquery.

Some links:

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

SELECT *
FROM Products
WHERE Id IN
(
    SELECT 
        P.Id
    FROM Products P
       JOIN Clicks C
          ON P.Id = C.Product_ID
    GROUP BY P.ID
    HAVING COUNT(1) > x
) A

or this, if you need only product id

    SELECT 
        P.Id
    FROM Products P
       JOIN Clicks C
          ON P.Id = C.Product_ID
    GROUP BY P.ID
    HAVING COUNT(1) > x

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.