有条件的MYSQL where子句

时间:2013-08-26 19:05:59

标签: mysql conditional case where

我有一个查询,如果一个名为OrderBy的标志是1那么它是一个日历事件,我需要检查两个日期时间字段之间的范围。而所有其他类型我们只是检查你正在查看的那一天。我研究if语句并看到很多帖子,其中建议使用一个案例,所以我试着将它实现到我的查询中。我的查询需要在哪里的条件。我知道我有语法问题,这就是为什么我在这里希望有人可以指出正确的方法来做到这一点。

感谢您的时间

我的查询目前

SELECT          activities.*, 
                activitytypes.orderby 
FROM            activities 
LEFT OUTER JOIN activitytypes 
ON              activities.typeid = activitytypes.typeid 
WHERE           activities.userid = 86 
AND             activities.typeid NOT IN ( 5, 
                                          10, 
                                          11, 
                                          12, 
                                          19 ) 
AND 
                CASE 
                                WHEN activities.orderby = 1 THEN activities.starttime >= '2013-08-26 04:00:00' 
                                AND             activities.endtime <= '2013-08-27 04:00:00' 
                                ELSE activities.activitydate = '2013-08-26' 
                                order BY        activitytypes.orderby, 
                                                activities.starttime

1 个答案:

答案 0 :(得分:18)

只要您使用足够的括号,就可以使用ANDOR执行此操作。

另外我假设activities.OrderBy可以为null。如果不是这种情况,您可以删除空检查:

SELECT activities.*, 
       activitytypes.orderby 
FROM   activities 
       LEFT OUTER JOIN activitytypes 
                    ON activities.typeid = activitytypes.typeid 
WHERE  activities.userid = 86 
       AND activities.typeid NOT IN ( 5, 10, 11, 12, 19 ) 
       AND ( ( activities.orderby = 1 
               AND activities.starttime >= '2013-08-26 04:00:00' 
               AND activities.endtime <= '2013-08-27 04:00:00' ) 
              OR ( ( activities.orderby IS NULL 
                      OR activities.orderby != 1 ) 
                   AND activities.activitydate = '2013-08-26' ) ) 
ORDER  BY activitytypes.orderby, 
          activities.starttime 

或者,如果您仍想使用CASE,则只需使用CASE关闭END语句,如下所示:

SELECT          activities.*, 
                activitytypes.orderby 
FROM            activities 
LEFT OUTER JOIN activitytypes 
ON              activities.typeid = activitytypes.typeid 
WHERE           activities.userid = 86 
AND             activities.typeid NOT IN ( 5, 
                                          10, 
                                          11, 
                                          12, 
                                          19 ) 
AND             ( 
                                CASE 
                                                WHEN activities.orderby = 1 THEN activities.starttime >= '2013-08-26 04:00:00' 
                                                AND             activities.endtime <= '2013-08-27 04:00:00' 
                                                ELSE activities.activitydate = '2013-08-26' 
                                end ) 
ORDER BY        activitytypes.orderby, 
                activities.starttime