用于Rails中复杂查询的正确SQL或ActiveRecord公式

时间:2014-04-06 02:34:01

标签: sql ruby-on-rails ruby activerecord

我有一个带有表sentiment_records的ActiveRecord模型SentimentRecords,其中每条记录都有属性:user_id,sentiment_id,lecture_id和timestamp。 我的查询:给定每个sentiment_id的LECTURE_ID和DATETIME,我想要计算每个sentiment_id记录了多少user_id(用户);对于每个user_id,仅计算最新的时间戳< =给定的日期时间。

这是一个不起作用的配方:

SentimentRecords.find_by_sql
("SELECT sentiment_id,count(*) 
FROM sentiment_records WHERE id          
IN (SELECT max(id) FROM sentiment_records 
WHERE lecture_id=LECTURE_ID GROUP BY user_id 
WHERE timestamp <= DATETIME) GROUP BY sentiment_id")

2 个答案:

答案 0 :(得分:0)

我不确定我是否理解这些要求,但我认为你需要SQL就是这样的。

select s1.sentiment_id, count(s1.user_id)
from sentiment_records s1
inner join (
    select user_id, max(timestamp) as timestamp
    from sentiment_records
    where timestamp <= ?
      and lecture_id = ?
    group by user_id
    ) s2 on s1.user_id = s2.user_id and s1.timestamp = s2.timestamp
where lecture_id = ?
group by s1.sentiment_id;

答案 1 :(得分:0)

这是正确的查询,感谢Nick Marden:

SentimentRecords.connection.select_all("SELECT sentiment_id, COUNT(*) FROM sentiment_records WHERE id IN (SELECT MAX(id) FROM sentiment_records WHERE lecture_id = LECTURE_ID AND timestamp < DATETIME GROUP BY user_id) GROUP BY sentiment_id")