I have a MySQL statement where I'm trying to exclude statements depending on where they "belong to" The query goes through, but it still shows the rows that I specifically said where its not equal to?
SELECT id, belongsto, title, madeby, sticky, locked, lastpost, posts
FROM threads
WHERE sticky !=1
AND belongsto !=12 OR sticky !=1 AND belongsto !=13
ORDER BY `threads`.`date` DESC
LIMIT 20
The WHERE clause can be combined with AND , OR , and NOT operators. The AND and OR operators are used to filter records based on more than one condition: The AND operator displays a record if all the conditions separated by AND are TRUE.
Description. The MySQL OR Condition is used to test two or more conditions where records are returned when any one of the conditions are met. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition.
The difference between AND, OR is that AND evaluates both conditions must be true for the overall condition to be true. The OR evaluates one condition must be true for the overall condition to be true. In the OR result, if name is John then condition will be true. If any row has the age 22, then it will be true.
You need parenthesis around your OR
statements to group them together logically.
WHERE sticky !=1
AND belongsto !=12 OR sticky !=1 AND belongsto !=13
should be:
WHERE (sticky !=1 AND belongsto !=12)
OR (sticky !=1 AND belongsto !=13)
or better yet:
WHERE sticky !=1 AND belongsto NOT IN(12,13)
If the goal is to exclude rows with belongsto values of 12
and 13
, then the OR
should be replaced with AND
.
The assertion (in the selected answer) that parentheses are "missing" and need to be added, is wrong. The addition of parentheses does not change the change the statement. The AND
operator already has a higher precedence than the OR
operator.)
WHERE sticky !=1
AND belongsto !=12 AND sticky !=1 AND belongsto !=13
^^^
Because it's unnecessary to repeat the same predicate twice, this could be rewritten as:
WHERE sticky !=1
AND belongsto !=12 AND belongsto !=13
Which can also be written as:
WHERE sticky !=1
AND NOT (belongsto =12 OR belongsto =13)
This can also be rewritten using a NOT IN (12,13)
(as demonstrated in the selected answer).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With