如何做从x等于多个值select?
所以我',debugging一些代码,并有以下的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。 所以我得到了所有types的广告的结果,而不仅仅是types13.每次查询被调用时,可能有很多县需要仰视或只是几个。
任何帮助正确的方式去这个将不胜感激。
把括号放在“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)
你可以尝试在ORexpression式中使用圆括号,以确保你的查询被正确解释,或者更简洁地使用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)