mysql - why sql query is selecting unnecessary values?

I want to select rows where the condition is true. I have a column named command, and if the column value contains defined (by me) strings, than add to result.

My problem is selecting the rows, because the query doesn't see the WHERE statement, it selects all the data if the column command contains the string.

SELECT * 
FROM `admin_log` 
WHERE `admin_log`.`user` = 'Admin' 
    AND command LIKE '%aznot%' 
    OR command LIKE '%hango%' 
ORDER BY `order_id` DESC 
LIMIT 0, 50

For example, I have 3 administrator accounts: Admin, Zuppa, Grund. I want to select all the data by account ADMIN if the command column contain: aznot or hango.

What am I doing wrong?

Answers


You need some parenthesis.

SELECT * 
FROM `admin_log`
WHERE `admin_log`.`user` = 'Admin'  
AND (command LIKE '%aznot%' OR command LIKE '%hango%')
ORDER BY `order_id` 
DESC LIMIT 0, 50

SELECT * FROM `admin_log` WHERE `admin_log`.`user` = 'Admin' 
 AND (command LIKE '%aznot%' OR command LIKE '%hango%') 
 ORDER BY `order_id` DESC LIMIT 0, 50

Try something like this:

SELECT * FROM `admin_log` WHERE `admin_log`.`user` = 'Admin' AND (command LIKE '%aznot%' OR command LIKE '%hango%') ORDER BY `order_id` DESC LIMIT 0, 50

It's better practice to separate the OR statements into a separate expression, to prevent misinterpretation by the engine.

SELECT * FROM `admin_log` WHERE `admin_log`.`user` = 'Admin' AND (command LIKE '%aznot%' OR command LIKE '%hango%') ORDER BY `order_id` DESC LIMIT 0, 50

SELECT * 
FROM   `admin_log` 
WHERE  `admin_log`.`user` = 'Admin' 
       AND (command LIKE '%aznot%'
        OR command LIKE '%hango%' )
ORDER  BY `order_id` DESC 
LIMIT  0, 50 

you need to properly nest the conditions. see the precedence rules for logical operators in SQL


Need Your Help

bootstrap: how to active a menu?

jsp twitter-bootstrap

I have a menu in my header.jsp file. like this:

MongoDB search to return only specific fields

mongodb pymongo

I'm using the $text feature in MongoDB to search for certain words and want the result to return not the entire document but only the specific fields where this word appears.