当我使用AND和OR对具有多个列的LIKE MySQL查询进行查询时,我的过滤器结果将导致查询,例如价格0和50000停止工作。如果我从LIKE语句中删除OR,则搜索工作正常。如何使用LIKE语句正确搜索多列?
这是一个无工作声明的示例,其中忽略了价格
SELECT *
FROM table
WHERE Price BETWEEN 0 AND 500000
AND class_id = 1
AND TotalSqFt BETWEEN 0 AND 999999999
AND Acres BETWEEN 0 AND 999999999
AND InclusionsFeatures LIKE '%horse%'
OR Remarks LIKE '%horse%'
ORDER
BY Price DESC
此语句正常工作,但现在我只能在一个列上执行LIKE查询。
SELECT * FROM table WHERE Price BETWEEN 0 AND 500000 AND class_id = 1 AND TotalSqFt BETWEEN 0 AND 999999999 AND Acres BETWEEN 0 AND 999999999 AND InclusionsFeatures LIKE '%horse%' ORDER BY Price DESC
答案 0 :(得分:4)
在第一条语句中,当您在最后一个AND之后添加OR时,Mysql会一直执行直到运行OR。如果通过OR条件,则AND之前的All将忽略。因此查询无法正确运行。
查看此查询:
SELECT
*
FROM
TABLE
WHERE
Price BETWEEN 0
AND 500000
AND class_id = 1
AND TotalSqFt BETWEEN 0
AND 999999999
AND Acres BETWEEN 0
AND 999999999
AND (InclusionsFeatures LIKE '%horse%' OR Remarks LIKE '%horse%' )
ORDER BY
Price DESC
通过将您的LIKES按括号分组,它将使用AND将括号内的条件与所有其他条件进行检查。因此,查询返回的数据将匹配括号内的条件和所有其他条件。
答案 1 :(得分:0)
您混用了AND
和OR
运算符。因此,您可以正确附上条件才能正常工作。对于您的OR
条件,可以将其围起来如下:
SELECT *
FROM table
WHERE (Price BETWEEN 0 AND 500000) AND
(class_id = 1) AND
(TotalSqFt BETWEEN 0 AND 999999999) AND
(Acres BETWEEN 0 AND 999999999) AND
(
(InclusionsFeatures LIKE '%horse%') OR (Remarks LIKE '%horse%')
)
ORDER BY Price DESC