mysql从tbl中选择字段,其中from_date不为null,to_date为null或不为null

时间:2014-05-26 16:01:41

标签: mysql

我有一个如下脚本:

while from_date is not null do
     if to_date is null then
          select * from product where now >= from_date; (1)
     else
          select * from product where from_date <= now <= to_date (2)
end while;

这意味着,如果from_date不为null且to_date为null,则需要选择产品。如果为null则为case(1),否则为null,则为case(2)。案例(1)和案例(2)都将添加产品以供选择。我想把它转换成mysql查询,请帮帮我!

演示表:

   id  |    from_date              |      to_date               |   item   |   price   |
    1      2014-03-14                   2014-06-26                   25         75
    2      2014-03-27                     NULL                       25         50
    3      2014-03-27                   2014-06-01                   26         80 
    4      2014-04-02                     NULL                       26         100 
    5          NULL                       NULL                       26         200

我想选择id为1到4的行,这是我想要的结果:)

1 个答案:

答案 0 :(得分:0)

select * from product 
where from_date is not null 
and to_date is null 
and now >=from_date

union all 

select * from product 
where from_date is not null 
and to_date is not null 
and now >= from_date 
and now <= to_date