简体   繁体   中英

Rails MySQL subquery count

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} products.select {|p| p.clicks.size > x} . How might one write a similar query for mysql?

Thanks!

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM