MySQL 如何从 x 等于多个值的地方进行选择?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/261783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do select from where x is equal to multiple values?
提问by Binarytales
I am debugging some code and have encountered the following SQL query (simplified version):
我正在调试一些代码并遇到以下 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
I'm getting very strange results from the query and I think its because the first OR is negating the AND operators that are found before it.
我从查询中得到了非常奇怪的结果,我认为这是因为第一个 OR 否定了在它之前找到的 AND 运算符。
This results in getting results back for ads of all types and not just for the type 13.
这会导致所有类型的广告获得结果,而不仅仅是类型 13。
Each time the query is called there may be a differnt amount of county entities that need to be looked up.
每次调用查询时,可能需要查找不同数量的县实体。
Any help on the correct way to go about this would be appreciated.
任何有关解决此问题的正确方法的帮助将不胜感激。
回答by Greg
Put parentheses around the "OR"s:
将括号括在“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
)
Or even better, use IN:
或者甚至更好,使用 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)
回答by Ned Batchelder
You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:
您可以尝试在 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)
回答by Ruben
And even simpler using IN:
使用 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)