当前位置:  开发笔记 > 后端 > 正文

如何从x等于多个值中选择?

如何解决《如何从x等于多个值中选择?》经验,为你挑选了3个好方法。

我正在调试一些代码并遇到以下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.

每次调用查询时,可能需要查找不同数量的县实体.

任何有关正确的方法的帮助将不胜感激.



1> Greg..:

将括号括在"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)


我认为IN版本更易于阅读,并且不太可能返回意外结果.
至少在MySQL上,它也快得多***

2> Ned Batcheld..:

您可以尝试在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)



3> Ruben..:

使用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)

推荐阅读
ifx0448363
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有