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
中有address
个George
或city
为Georgetown
,则会返回0
人。
我怎样才能这样做只会让那些拥有1
到OR
辆汽车的人回来,他们的名字是乔治或乔治城镇?
所以我认为我使用了错误的{{1}}声明?但是我的声明很难改进。 任何建议都很可爱。
答案 0 :(得分:5)
您需要在parenthesis
子句中使用where
来正确过滤行。
在您的查询中,即使Cars
不在0
和1
以及Address LIKE ('%George%')
之间,也会返回该行,因为and
运算符已应用仅在name
和cars
之间。
要避免这种情况,只需将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
请记住,如果某些内容已更新,您需要更新"搜索"值也与新数据有关。