如何更好地改进此SQL查询?

时间:2015-01-20 16:38:01

标签: php sql

SELECT  * 
FROM    `people` 
WHERE   `Cars` BETWEEN '0' AND '1' 
AND     `Name` LIKE ('%George%') 
    OR  `Address` LIKE ('%George%') 
    OR  `City` LIKE ('%George%') 
ORDER BY Favorite DESC

目前,如果2 cars中有addressGeorgecityGeorgetown,则会返回0人。

我怎样才能这样做只会让那些拥有1OR辆汽车的人回来,他们的名字是乔治或乔治城镇?

所以我认为我使用了错误的{{1}}声明?但是我的声明很难改进。 任何建议都很可爱。

6 个答案:

答案 0 :(得分:5)

您需要在parenthesis子句中使用where来正确过滤行。

在您的查询中,即使Cars不在01以及Address LIKE ('%George%')之间,也会返回该行,因为and运算符已应用仅在namecars之间。

要避免这种情况,只需将parenthesis添加到OR运算符的列中即可。尝试此操作。

SELECT  * 
FROM    `people` 
WHERE   `Cars` BETWEEN '0' AND '1' 
AND     (`Name` LIKE ('%George%') 
    OR  `Address` LIKE ('%George%') 
    OR  `City` LIKE ('%George%')) 
ORDER BY Favorite DESC

答案 1 :(得分:2)

您遇到的问题是and的优先级高于or

您的查询被解释为:

SELECT  * 
FROM    `people` 
WHERE   (
            `Cars` BETWEEN '0' AND '1' 
            AND     `Name` LIKE ('%George%')
        ) 
        OR  `Address` LIKE ('%George%') 
        OR  `City` LIKE ('%George%')) 
        ORDER BY Favorite DESC

使用括号内的or子句更好地编写查询:

SELECT  * 
FROM    `people` 
WHERE   `Cars` BETWEEN '0' AND '1' 
AND     (
            `Name` LIKE ('%George%') 
            OR  `Address` LIKE ('%George%') 
            OR  `City` LIKE ('%George%')
        )
ORDER BY Favorite DESC

答案 2 :(得分:1)

()中的OR语句分组,以使其中一个必须为真:

SELECT  * 
FROM    `people` 
WHERE   `Cars` BETWEEN '0' AND '1' 
AND     (
        `Name` LIKE ('%George%') OR
        `Address` LIKE ('%George%') OR
        `City` LIKE ('%George%')
        )
ORDER BY Favorite DESC

答案 3 :(得分:1)

显然没有。汽车不能是分数,所以应该用来检查0或1

SELECT  * 
FROM    `people` 
WHERE   `Cars` in(0,1) 
AND     (`Name` LIKE ('%George%') 
    OR  `Address` LIKE ('%George%') 
    OR  `City` LIKE ('%George%')) 
ORDER BY Favorite DESC

答案 4 :(得分:0)

尝试添加“()”:

SELECT  * 
FROM    `people` 
WHERE   `Cars` BETWEEN '0' AND '1' 
AND     (`Name` LIKE ('%George%') 
    OR  `Address` LIKE ('%George%') 
    OR  `City` LIKE ('%George%') )
ORDER BY Favorite DESC

答案 5 :(得分:0)

如果您愿意,您只能获取一列,并且稍后可以添加更多数据。 我的意思是添加名为" search"并抛出您想要的所有数据,并仅通过此搜索。

SELECT  * FROM    `people` 
WHERE   `Cars` BETWEEN '0' AND '1' 
AND     `search` LIKE ('%George%')
ORDER BY Favorite DESC

请记住,如果某些内容已更新,您需要更新"搜索"值也与新数据有关。