Answer the question
In order to leave comments, you need to log in
Excluding certain IDs with an OR condition doesn't work correctly?
Suppose that I have a database of movies with genres and I would like to make it possible to exclude certain genres with the OR condition, i.e. if the film has at least one of the excluded genres, it should be excluded from the selection. It would seem a trivial task. OK. Because we will use Ruby on Rails, we will not write raw sql queries, right? Therefore, for these purposes, I found the appropriate Gem and was able, it would seem quite logical, to make a request, I will not bother you with the implementation, if you are interested, you can look at my question on Stackoverflow , where, unfortunately, they are not in a hurry to answer me.
Let me just say that the final MySQL query that forms the active record is something like this
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`;
Answer the question
In order to leave comments, you need to log in
One of those situations where M2M is not ice.
Do exclude roughly speaking
SELECT `movies`.* FROM `movies`
INNER JOIN `movie_genres` ON `movie_genres`.`movie_id` = `movies`.`id`
WHERE 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 (10,12)
)
GROUP BY `movies`.`id`;
What's the question? If you are wondering what is wrong with the RoR request, then it would be useful to see it.
The sql query itself looks too strange, since the genre_id in any way cannot be equal to 10 and 12 at the same time. If I understood the task correctly (here it is also not described), then you need to do AND instead of OR. That is, if the movie does not have genre 10 and does not have genre 12.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question