在where子句中使用if语句

时间:2011-05-15 18:51:53

标签: mysql if-statement where-clause

如果在where语句中我试图获取datetime大于NOW()的所有行,但是如果type ='economy',我想约束它只显示datetime和NOW之间的datediff( )大于14天。

类似:

Select type,date(datetime) as date
from tbl1
where datetime > NOW()
IF(type = 'economy') && datediff(datetime,NOW()) > 14
order by datetime desc

我也曾尝试过案例,但无法弄清楚......

3 个答案:

答案 0 :(得分:10)

您可以将标准分为两种不同的比较:

select type,date(datetime) as date 
from tbl1 
where (datetime > NOW() AND type <> 'economy') OR
      (datediff(datetime, NOW()) > 14 AND type = 'economy')
order by datetime desc

(未检查语法错误,但想法应该是正确的......)

答案 1 :(得分:2)

WHERE ((type <> 'economy') AND (datetime > now)) OR ((type = 'economy') AND (datediff(datetime,NOW()) > 14)

答案 2 :(得分:2)

SELECT type, date(datetime) AS date 
FROM tbl1 
WHERE ( type <> 'economy' AND datetime > NOW() ) 
    OR ( type = 'economy' AND datediff(datetime, NOW()) > 14 )