New to SQL but I’m trying to find titles
wherein the words “blue” and “black” are present. However, they cannot be from users who have ids of 1 and 5. This is what I did:
SELECT title, id_card FROM site WHERE (title LIKE "%blue%" OR title LIKE "%black%") AND (id_card != 1 OR id_card != 5) ORDER BY id_card ASC;
However, when I add that id 1 and id 5 shouldn’t be in the query, it shows me something like this:
Blog Title | User |
---|---|
The blue sky was so nice today | 1 |
Black is my favorite color | 2 |
I’m feeling blue | 2 |
She was dressed in black | 3 |
However, when I erase id_card != 5
from the code, it works perfectly fine.
Blog Title | User |
---|---|
Black is my favorite color | 2 |
I’m feeling blue | 2 |
She was dressed in black | 3 |
I’m just wondering where I went wrong and how I can fix this issue. Thank you in advance!
Advertisement
Answer
You are on the right track. But use not in
to get the logic right:
SELECT title, id_card FROM site WHERE (title LIKE '%blue%' OR title LIKE '%black%') AND id_card NOT IN (1, 5) ORDER BY id ASC;
You could also fix your logic by using AND
.