我正在调试一些代码并遇到以下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的结果。
每次调用查询时,可能需要查找不同数量的县实体。
任何有关正确方法的帮助都将受到赞赏。
答案 0 :(得分:117)
将括号括在“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)
答案 1 :(得分:19)
您可以尝试在OR表达式周围使用括号,以确保正确解释您的查询,或者更简洁地使用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)
答案 2 :(得分:13)
使用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)