mysql - 为什么sql查询选择不必要的值?

时间:2012-06-13 12:47:15

标签: mysql conditional-statements

我想选择条件为真的行。我有一个名为command的列,如果列值包含已定义的(由我)字符串,则添加到结果。

我的问题是选择行,因为查询没有看到WHERE语句,如果列command包含字符串,它会选择所有数据。

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

例如,我有3个管理员帐户:Admin,Zuppa,Grund。如果命令列包含:aznot或hango,我想通过帐户ADMIN选择所有数据。

我做错了什么?

6 个答案:

答案 0 :(得分:2)

你需要一些括号。

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

尝试这样的事情:

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

答案 3 :(得分:1)

最好将OR语句分成单独的表达式,以防止引擎误解。

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

答案 4 :(得分:1)

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 

答案 5 :(得分:1)

您需要正确嵌套条件。请参阅SQL

中逻辑运算符的优先规则