0

假设我有一个包含流派的电影数据库,我想显示除某些特定流派之外的所有电影。我已经建立了所有协会并且工作得很好。

为此,我遇到了名为Squeel的 gem ,并编写了这段代码

movies = Movie.joins(:movie_genres).approved

# This is just an array of id's
included_genres = params[:genres][:included_genres]
excluded_genres = params[:genres][:excluded_genres]

if included_genres

  # This works just fine
  movies = movies.where(movie_genres: {genre_id: included_genres})

  # This works too but IMO MySQL IN operator is faster.
  #movies = movies.where{movie_genres.genre_id.eq_any included_genres}

end

if excluded_genres

  # Here is where the problems occurs, it generates perfectly nice SQL 
  # but for some reason it doesn't work as expected.
  movies = movies.where{movie_genres.genre_id.not_eq_any excluded_genres}

  # If we do it this way, it will only not match those movies 
  # that have all the selected genres at once, i need to match 
  # all movies that have atleast one of the inputted genres
  #movies = movies.where("genre_id NOT IN (?)", excluded_genres)
  #movies = movies.where{movie_genres.genre_id.not_eq_all excluded_genres}    

end

movies = movies.group(:id)

所以,是的,多亏了 Squeel,我们得到了这个 SQL:

SELECT `movies`.* FROM `movies` 
INNER JOIN `movie_genres` ON `movie_genres`.`movie_id` = `movies`.`id` 
WHERE ((`movie_genres`.`genre_id` != 10 OR `movie_genres`.`genre_id` != 12)) 
GROUP BY `movies`.`id`;

这没有包括类型,因为它们按预期工作。

因此,结果,where 条件看起来甚至不适用,因为我认为有或没有它没有区别。

看截图: 显示 sql 查询工作的 Mysql 终端输出

有谁知道为什么它不起作用,我应该从哪里开始挖掘?

非常感谢所有帮助。

4

2 回答 2

1

问题在于逻辑,而不是 sql。使用“或”逻辑,您希望获得满足任何条件的行,因此对于您的查询,您将获得 id 为 10 的行,因为 10 != 12。使用 WHERE IN - 很好的方式

于 2012-12-30T22:58:22.033 回答
0

通过使用命名范围解决了这个问题

scope :excluding_genres, 
  lambda { |genres| { 
    :conditions => 
       ['movies.id NOT IN 
       (SELECT movies.id FROM movies 
        LEFT JOIN movie_genres ON movies.id = movie_genres.movie_id 
        WHERE movie_genres.genre_id IN (?))', genres] 
  }}
于 2012-12-30T22:35:33.947 回答