V
V
Vitali2013-12-31 00:53:45
MySQL
Vitali, 2013-12-31 00:53:45

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`;

But not very working. See screenshot
m7S6G.png
Despite the fact that the record seems to fall under the condition (the movie has a genre of 10), it is still shown.
What could be the problem and where should I start digging?
Thank you very much.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
edogs, 2013-12-31
@Screatch

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`;

N
nochkin, 2013-12-31
@nochkin

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.

A
Aleks_ja, 2013-12-31
@Aleks_ja

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

Like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question