日期选择..不会工作

时间:2015-09-07 09:38:30

标签: postgresql

我有一个问题。执行以下SQL查询时:

SELECT order_id, orderdatum, plaats
FROM order_row 
INNER JOIN order_row_oneoff ON order_row.order_row_id = order_row_oneoff.order_row_oneoff_id
INNER JOIN orders ON order_row.order_id = orders.ordernr
WHERE orderdatum >= '2015-09-01'
AND orderdatum < '2015-09-05'
AND order_row.product_id = '4118' OR order_row.product_id = '4128' OR order_row.product_id = '4176' AND orders.orderstatus > 98 

它只选择所有内容并忽略日期。 但是当你删除第二个AND子句时,它可以工作。为什么呢?

2 个答案:

答案 0 :(得分:1)

and的{​​{3}}更高,这意味着and的绑定强于or。使用括号将条件放在一起

where orderdatum >= '2015-09-01'
and orderdatum < '2015-09-05'
and 
(
   order_row.product_id = '4118' 
   or  order_row.product_id = '4128' 
   or order_row.product_id = '4176'
)
and orders.orderstatus > 98 

或在您的情况下使用IN

where orderdatum >= '2015-09-01'
and orderdatum < '2015-09-05'
and order_row.product_id in ('4118', '4128' , '4176')
and orders.orderstatus > 98 

答案 1 :(得分:0)

实际上你在最后一个问题,因为你应该使用IN运算符而不是AND

 product_id IN ('4118', '4128' , '4176')