我正在调试一些代码并遇到以下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)
您可以尝试在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)
使用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)