PHP与mysql查询未返回预期结果

时间:2019-04-09 21:51:10

标签: php mysql sql

我是PHP的新手,我试图在我的表中选择记录(用于搜索功能),该表中的月份是静态的,其他列则有所不同

下面是查询

SELECT * 
FROM issue 
WHERE month = "Apr 2019" 
    AND issue LIKE "%ekh%" 
    OR issue_type LIKE "%ekh%" 
    OR facility LIKE "%ekh%" 
    OR issue_id LIKE "%ekh%" 
    OR priority LIKE "%ekh%" 
ORDER BY issue_id DESC

这是返回所有满足like子句的行,即使month isnt =“ Apr 2019”。

2 个答案:

答案 0 :(得分:2)

在代数中,AND操作在OR操作之前完成。这与您的WHERE子句中的规则相同。

您可以使用这样的括号来解决此问题:

SELECT *
FROM issue
WHERE month = "Apr 2019"
    AND (issue LIKE "%ekh%"
        OR issue_type LIKE "%ekh%"
        OR facility LIKE "%ekh%"
        OR issue_id LIKE "%ekh%"
        OR priority LIKE "%ekh%")
ORDER BY issue_id DESC

答案 1 :(得分:1)

当mysql首先命中or时,它会自动返回所有内容,因为or something is true。因此,您应该使用括号:

SELECT *
FROM issue
WHERE month = "Apr 2019" AND
(issue like "%ekh%" OR
 issue_type like "%ekh%" OR
 facility like "%ekh%" OR
 issue_id like "%ekh%" OR
 priority like "%ekh%")
ORDER BY issue_id DESC