superUntitled
superUntitled

Reputation: 22527

mySql: `SELECT`` statement with `OR` and `AND`

I am confused about why I am getting rows returned from a query...

Here is the query, it searches for the existence of a string in a single table.

SELECT * 
  FROM `donor` 
 WHERE `col1` LIKE '%test%' 
    OR `col2` LIKE '%test%' 
    OR `col3` LIKE '%test%' 
    OR `col4` LIKE '%test%' 
   AND `delete` = 0

The last line AND delete = 0 is returning rows whose 'delete' column is '1'? Does anyone have an idea of why this is happening?

Upvotes: 1

Views: 212

Answers (2)

Jack Murdoch
Jack Murdoch

Reputation: 2894

You'll need to group the conditions together by enclosing them in brackets (). Try this:

SELECT * FROM `donor` WHERE 
(`col1` LIKE '%test%' OR 
`col2` LIKE '%test%' OR 
`col3` LIKE '%test%' OR 
`col4` LIKE '%test%') AND
`delete` =0

Upvotes: 1

rsbarro
rsbarro

Reputation: 27339

Rewrite the WHERE clause as follows:

SELECT * FROM `donor` WHERE 
(`col1` LIKE '%test%' OR 
`col2` LIKE '%test%' OR 
`col3` LIKE '%test%' OR 
`col4` LIKE '%test%')
AND `delete` =0

You want to or the first set of criteria together and then perform the AND operation.

Upvotes: 4

Related Questions