BETWEEN和OR选择

时间:2011-03-15 16:59:25

标签: mysql sql

如何过滤到日期范围

Select * from  XXX where date between DATE1 AND DATE2 OR Between DATE3 AND DATE4

(从更新中复制回复)

这是我的条件

WHERE  ( items_count != '0' )
       AND ( main_table.is_active = '1' )
       AND ( main_table.store_id IN ( '0', '1' ) )
       AND ( main_table.updated_at BETWEEN
             '2011-03-04 16:52:19' AND '2011-03-05 16:52:19'
           )
        OR ( main_table.updated_at BETWEEN
             '2011-03-13 16:52:19' AND '2011-03-14 16:52:19'
           )
LIMIT  0, 30  

第一个条件从未使用过

4 个答案:

答案 0 :(得分:3)

Select * from  XXX 
  where (date between DATE1 AND DATE2) 
        OR 
        (date between DATE3 AND DATE4)

编辑:

试试这个:

WHERE items_count != '0' AND 
      main_table.is_active = '1' AND 
      main_table.store_id IN ('0', '1') AND 
      (  main_table.updated_at BETWEEN '2011-03-04 16:52:19' AND '2011-03-05 16:52:19' 
         OR 
         main_table.updated_at BETWEEN '2011-03-13 16:52:19' AND '2011-03-14 16:52:19'
      )

答案 1 :(得分:1)

将它们视为独立条件:

select * from xxx where (date between date1 and date2) or (date between date3 and date4);

答案 2 :(得分:1)

像这样:

 select * from XXX 
 where (date between DATE1 AND DATE2) 
    or (date between DATE3 AND DATE4)

答案 3 :(得分:1)

一些OCD总是有助于SQL ......

你不需要你拥有的所有括号,但是OR没有按照你期望的方式工作。

.... 
   WHERE 
    items_count != '0'        
    AND 
    main_table.is_active = '1'        
    AND 
    main_table.store_id IN ('0', '1')
    AND (
      main_table.updated_at
      BETWEEN '2011-03-04 16:52:19'
      AND '2011-03-05 16:52:19'
      OR 
      main_table.updated_at
      BETWEEN '2011-03-13 16:52:19'
      AND '2011-03-14 16:52:19'
    )
    LIMIT 0 , 30