我试图按喜欢的数量排序所有电影(即使他们还没喜欢)。我有以下工作sql语句:
SELECT *, COUNT(case when movie_votes.like = 1 then 1 end) AS count_likes
FROM movies
LEFT OUTER JOIN movie_votes
ON movie_votes.movie_id = movies.id
GROUP BY movie_id
ORDER BY count_likes;
我想在我的控制器中实现它。到目前为止,我有:
Movie.select("*, COUNT(case when 'movie_votes'.'like'=1 then 1 end) AS count_likes").joins("LEFT OUTER JOIN 'movie_votes' ON 'movies'.'id'='movie_votes'.'movie_id'").group("'movie_id'")
哪些输出形成控制台:
SELECT *, COUNT(case when 'movie_votes'.'like'=1 then 1 end AS count_likes FROM `movies` LEFT OUTER JOIN 'movie_votes' ON 'movie'.'id'='movie_votes'.'movie_id' GROUP BY 'movie_id'
和一个Mysql2 ::错误:你的SQL语法有错误; 我做错了没有语法吗?
答案 0 :(得分:0)
对于那些可能会觉得有用的人:
scope :order_by_likes_or_hates, lambda {|type|
select("*, COUNT(case when movie_votes.like=#{type} then 1 end) AS count_likes").joins("LEFT OUTER JOIN movie_votes ON movies.id=movie_votes.movie_id").group("movie_votes.movie_id").order("count_likes DESC")}
如果有人可以提供更干净的版本,请执行。