0

我一直对以下查询感到困惑,以及如何使用活动记录来完成。

select * from links where id in 
    (select id from 
        (select votable_id as id, count(votable_id) as count from votes where vote_scope = 'flag' and votable_type = 'Link' group by votable_id ) 
     as x where count < 3);

我目前在我的 finder 中使用原始 SQL 查询find_by_sql

编辑

感谢 Joachim Isaksson,查询可以压缩到

select * from links where id in 
    (select votable_id from votes 
     where vote_scope = 'flag' 
     and votable_type = 'Link' 
     group by votable_id 
     HAVING COUNT(*) < 3) ;
4

1 回答 1

1

让我们从我不以任何身份成为 Rails 专家开始,我无法测试运行它,所以有点“盲目”。换句话说,把这个和一粒盐放在一起:)

将您的查询重写为连接(假设这里您的链接表有并且为了;而id调用了另外一个字段。linkGROUP BY

SELECT links.* 
FROM links
JOIN votes
  ON links.id = votes.votable_id
 AND votes.vote_scope = 'flag'
 AND votes.votable_type = 'Link'
GROUP BY votes.votable_id, links.id, links.link
HAVING COUNT(*) < 3;

(用于测试的 SQLfiddle)

...应该使这样的工作(为了便于阅读而拆分行)

Link.joins("JOIN votes ON links.id = votes.votable_id
            AND votes.vote_scope = 'flag' AND votes.votable_type = 'Link'")
    .group("votes.votable_id, links.id, links.link")
    .having("COUNT(*) < 3")

正确设置关联也可以让您以更“有条理”的方式进行连接

于 2013-05-25T11:14:25.043 回答