使用MySQL子查询

时间:2015-04-23 21:00:26

标签: mysql sql

这是我的PHP脚本创建的查询。查询执行成功没有任何错误,但结果我不期望。我希望此查询结果中的行包含所有三个关键字(3D,设计,PAG)。但是,即使找到一个关键词,它现在也会返回结果。如何修改查询?

SELECT ID
FROM  `catiascripts` 
WHERE  `ID` LIKE  '%3D%'
OR  `ScriptName` LIKE  '%3D%'
OR  `ScriptApplication` LIKE  '%3D%'
OR  `ScriptDescription` LIKE  '%3D%'
OR  `Customer` LIKE  '%3D%'
AND ID
IN (

SELECT ID
FROM  `catiascripts` 
WHERE  `ID` LIKE  '%design%'
OR  `ScriptName` LIKE  '%design%'
OR  `ScriptApplication` LIKE  '%design%'
OR  `ScriptDescription` LIKE  '%design%'
OR  `Customer` LIKE  '%design%'
)
AND ID
IN (

SELECT ID
FROM  `catiascripts` 
WHERE  `ID` LIKE  '%PAG%'
OR  `ScriptName` LIKE  '%PAG%'
OR  `ScriptApplication` LIKE  '%PAG%'
OR  `ScriptDescription` LIKE  '%PAG%'
OR  `Customer` LIKE  '%PAG%'
)
LIMIT 0 , 30

2 个答案:

答案 0 :(得分:3)

您的SELECT BlockID FROM AvailabilityBlocks ORDER BY BlockID; 表达式需要括号。您违反了MySQL的操作顺序,因此您必须使用适当的and/or强制执行自己的操作。

()的优先级高于and,因此您的查询:

or

正在执行

SELECT   p OR q OR r AND x OR y OR z ...

你想要

SELECT p OR q OR (r AND x) OR y OR Z

相关文档:https://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html

答案 1 :(得分:1)

SELECT ID
FROM `catiascripts` 
WHERE (
       `ID` LIKE '%3D%'
    OR `ScriptName` LIKE '%3D%'
    OR `ScriptApplication` LIKE '%3D%'
    OR `ScriptDescription` LIKE '%3D%'
    OR `Customer` LIKE '%3D%'
)
AND (
       `ID` LIKE '%design%'
    OR `ScriptName` LIKE '%design%'
    OR `ScriptApplication` LIKE '%design%'
    OR `ScriptDescription` LIKE '%design%'
    OR `Customer` LIKE '%design%'
)
AND (
       `ID` LIKE '%PAG%'
    OR `ScriptName` LIKE '%PAG%'
    OR `ScriptApplication` LIKE '%PAG%'
    OR `ScriptDescription` LIKE '%PAG%'
    OR `Customer` LIKE '%PAG%'
)
LIMIT 0 , 30