将所有订单发送到纽约

时间:2015-02-25 17:58:04

标签: mysql sql select

orders表格中有billing_state个字段和shipping_state字段。我需要获得运往纽约州的订单。假设订单已开票并运往纽约州。在这种情况下,billing_state字段的值为NY,ship_state的值为null。一个订单从CA发出并运到纽约。 billing_state值为CA,shipping_state为NY。

现在应该在结果中获取两行的查询是什么?

SELECT * 
FROM orders 
WHERE dateord>='2014-02-25' 
AND dateord<='2014-02-25' 
AND activeFlag=1 
AND (ship_state='NY' 
     OR (billing_state = 'NY' AND ship_state='')) 
order by ordId  

5 个答案:

答案 0 :(得分:4)

你快到了,

SELECT * 
FROM orders 
WHERE dateord>='2014-02-25' 
AND dateord<='2014-02-25' 
AND activeFlag=1 
AND (ship_state='NY' 
     OR (billing_state = 'NY' AND ship_state IS NULL)) 
order by ordId 

对于大多数DBMS(Oracle是一个例外,包括MySQL)''NULL是不同的值。

您可能需要重新检查验证

WHERE dateord>='2014-02-25' AND dateord<='2014-02-25'

正如说法一样

WHERE dateord = '2015-02-25'

答案 1 :(得分:2)

Null''是不同的事情。如果是实际null,则需要使用is运算符:

SELECT   * 
FROM     orders 
WHERE    dateord >= '2014-02-25' AND 
         dateord <= '2014-02-25' AND 
         activeFlag = 1 AND 
         (ship_state='NY' OR 
          (billing_state = 'NY' AND ship_state IS NULL)) 
ORDER BY ordId  

答案 2 :(得分:2)

如果ship_state为NULL,则将其与空字符串进行比较将不会生成匹配项。如果dateord是时间戳,,它包含时间部分,您还需要修改日期过滤器。

如果ship_state为NULL并且dateord是时间戳,请尝试以下WHERE语句。

WHERE (dateord >= '2014-02-25')
  AND (dateord < '2014-02-25' + INTERVAL 1 DAY)
  AND (activeFlag = 1)
  AND (COALESCE(`ship_state`, `billing_state`) = 'NY')

答案 3 :(得分:0)

您应该使用is null代替= ''

答案 4 :(得分:0)

尝试Union子句:

SELECT * 
FROM orders 
WHERE dateord>='2014-02-25' 
AND dateord<='2014-02-25' 
AND activeFlag=1 
AND ship_state='NY'
order by ordId

union all

SELECT * 
FROM orders 
WHERE dateord>='2014-02-25' 
AND dateord<='2014-02-25' 
AND activeFlag=1 
AND ship_state is null
AND billing_state = 'NY'
order by ordId