Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Where Or?

Tags:

sql

mysql

where

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
like image 355
Necro. Avatar asked Jul 30 '13 17:07

Necro.


People also ask

Can I use or in WHERE SQL?

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.

Is or used in MySQL?

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.

Can we use 2 WHERE clause in SQL?

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.

What is the difference between AND and/or in MySQL?

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.


2 Answers

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)
like image 68
John Conde Avatar answered Oct 22 '22 01:10

John Conde


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).

like image 3
spencer7593 Avatar answered Oct 22 '22 01:10

spencer7593