sql:如何使用如此多的ands正确形成where子句

时间:2011-12-21 12:53:46

标签: sql

以下是忽略日期范围。有人可以解释这里出了什么问题吗?不确定某些声明是否需要围绕它的括号,但无论如何都不会理解为什么。

WHERE
     booking_date BETWEEN '2011-11-01' AND '2011-12-21'
 AND booking_status = 'Confirmed'
  OR booking_status = 'Cancelled'
  OR booking_status = 'Rearranged'
 AND invoice_number=''
ORDER BY booking_date ASC

4 个答案:

答案 0 :(得分:6)

在您的OR条件中加上括号:

WHERE
     booking_date BETWEEN '2011-11-01' AND '2011-12-21'
 AND (booking_status = 'Confirmed'
      OR booking_status = 'Cancelled'
      OR booking_status = 'Rearranged')
 AND invoice_number=''
ORDER BY booking_date ASC

您还可以使用IN,这可能更容易阅读和理解:

WHERE
     booking_date BETWEEN '2011-11-01' AND '2011-12-21'
 AND booking_status IN ('Confirmed', 'Cancelled', 'Rearranged')
 AND invoice_number=''
ORDER BY booking_date ASC

答案 1 :(得分:4)

AND比OR高precedence。您的代码被解释为:

WHERE (booking_date BETWEEN '2011-11-01' AND '2011-12-21'
       AND booking_status = 'Confirmed')
OR (booking_status = 'Cancelled')
OR (booking_status = 'Rearranged' AND invoice_number='')

我建议使用IN:

而不是使用OR
WHERE booking_date BETWEEN '2011-11-01' AND '2011-12-21'
AND booking_status IN ('Confirmed', 'Cancelled', 'Rearranged')
AND invoice_number=''

答案 2 :(得分:2)

这可能是你想要的:

WHERE booking_date BETWEEN '2011-11-01' AND '2011-12-21'
AND (booking_status = 'Confirmed' OR booking_status = 'Cancelled' OR booking_status = 'Rearranged')
AND invoice_number=''
ORDER BY booking_date ASC"

添加的换行符只是为了更容易阅读。重要的部分是括号。

请查看此页面以获取有关运算符优先级的说明:http://msdn.microsoft.com/en-us/library/ms190276.aspx

答案 3 :(得分:0)

可能是你OR给你的问题:

重新格式化:

WHERE booking_date BETWEEN '2011-11-01' AND '2011-12-21' 
AND (booking_status = 'Confirmed' 
    OR booking_status = 'Cancelled' 
    OR booking_status = 'Rearranged') 
AND invoice_number=''
ORDER BY booking_date ASC

您可以添加括号以使其执行您想要的操作(如上所述),或者您甚至可以使用IN子句:

WHERE booking_date BETWEEN '2011-11-01' AND '2011-12-21' 
AND booking_status IN ( 'Confirmed', 'Cancelled', 'Rearranged') 
AND invoice_number=''
ORDER BY booking_date ASC