MySQL查询有LIKE和AND子句

时间:2013-04-10 00:35:07

标签: mysql sql

我有以下查询:

$query="SELECT * FROM products 
                 WHERE  productname LIKE '%$searchterm%' 
                 OR shortdescription LIKE '%$searchterm%' 
                 OR description LIKE  '%$searchterm%' AND VISIBLE != 0";

查询返回我想要的记录,但也返回visible = 0的记录。

谁能告诉我我做错了什么?

的问候,卓然

2 个答案:

答案 0 :(得分:1)

使用括号:

SELECT 
    * 
FROM 
    products 
WHERE  
    (
        productname LIKE '%$searchterm%' 
     OR shortdescription LIKE '%$searchterm%' 
     OR description LIKE  '%$searchterm%'
    ) 
AND VISIBLE != 0

答案 1 :(得分:1)

大概是operator precedence

运营商AND首先运行OR

所以你的查询是这样的:

$query="SELECT * FROM products 
                 WHERE  productname LIKE '%$searchterm%' 
                 OR shortdescription LIKE '%$searchterm%' 
                 OR (description LIKE  '%$searchterm%' AND VISIBLE != 0");

修复您的查询:

$query="SELECT * FROM products 
                 WHERE  (productname LIKE '%$searchterm%' 
                 OR shortdescription LIKE '%$searchterm%' 
                 OR description LIKE  '%$searchterm%') AND VISIBLE != 0";