我正在调试一些代码,并且遇到了以下SQL查询(简化版):
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9
我从查询中得到了非常奇怪的结果,并且我认为这是因为第一个OR取反了之前找到的AND运算符。
这样一来,不仅所有类型13的广告都能获得所有类型广告的结果。
每次调用查询时,可能都需要查询不同数量的县实体。
任何对解决此问题的正确方法的帮助将不胜感激。
最佳答案
在“OR”周围加上括号:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND
(
ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9
)
甚至更好,使用IN:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)
关于sql - 如何从x等于多个值的位置进行选择?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/261783/