具有多个WHERE的MYSQL查询

时间:2014-08-14 17:31:59

标签: mysql sql

我有一个非常大的数据库。我需要运行查询以通过电子邮件和load_date(日期/时间戳字段)进行搜索。我需要从3个不同的日期中抽出3个电子邮件用户。

所以我需要一个表来显示电子邮件(电子邮件字段):

email1@host.com
nextemail@site.com
finalemail.yosite.com

表示日期(load_date字段):

2014-08-01
2014-08-06
2014-08-09

如果我这样做:

SELECT email, load_date
  FROM table1
  WHERE email = 'email1@host.com' or email = 'nextemail@site.com' or email = 'finalemail.yosite.com

结果是正确的。

如果我跑:

SELECT email, load_date
  FROM table1
  WHERE load_date LIKE "2014-08-01%" or load_date LIKE "2014-08-06%" or load_date LIKE "2014-08-09%"

结果是正确的。

但如果我把它们结合起来:

SELECT email, load_date
  FROM table1
  WHERE email = 'email1@host.com' or email = 'nextemail@site.com' or email = 'finalemail.yosite.com'
  and
   load_date LIKE "2014-08-01%" or load_date LIKE "2014-08-6%" or load_date LIKE "2014-08-09%"

我得到了一切!?

我做错了什么?

3 个答案:

答案 0 :(得分:3)

AND函数具有比OR函数更高的优先级。您需要将OR包含在括号中。

SELECT email, load_date
FROM table1
WHERE (email = 'email1@host.com' or email = 'nextemail@site.com' or email = 'finalemail.yosite.com')
and (load_date LIKE "2014-08-01%" or load_date LIKE "2014-08-6%" or load_date LIKE "2014-08-09%")

答案 1 :(得分:3)

您需要使用括号:

SELECT email, load_date
  FROM table1
  WHERE (email = 'email1@host.com' or email = 'nextemail@site.com' or email = 'finalemail.yosite.com'(
  and
   (load_date LIKE "2014-08-01%" or load_date LIKE "2014-08-6%" or load_date LIKE "2014-08-09%")

答案 2 :(得分:0)

二元运算符从左到右进行评估,and优先于or

示例:如果condX是布尔条件,则cond1 or cond2 and cond3 or cond4的评估如下:

  1. cond1或cond2
  2. [上述结果]和cond3
  3. [上述结果]和cond4
  4. 如果你想"改变"您的条件的评估顺序,您必须将它们括在括号中。

    在您的具体情况下,您必须在括号内括出email比较和load_date比较:

    WHERE 
        (email = 'email1@host.com' or email = 'nextemail@site.com' or email = 'finalemail.yosite.com')
      and (load_date LIKE "2014-08-01%" or load_date LIKE "2014-08-6%" or load_date LIKE "2014-08-09%")
    

    备选方案:使用in

    WHERE email in ('email1@host.com', 'nextemail@site.com', 'finalemail.yosite.com')
      AND date(load_date) in ("2014-08-01", "2014-08-6", "2014-08-09")
    -- date(load_date) extracts the date part of the field