gpt4 book ai didi

mysql - MYSQL where 子句中的条件

转载 作者:可可西里 更新时间:2023-11-01 06:54:33 25 4
gpt4 key购买 nike

我有一个查询,如果名为 OrderBy 的标志为 1,则它是一个日历事件,我需要检查两个日期时间字段之间的范围。而所有其他类型,我们只检查您查看的日期。我研究了 if 语句并看到许多建议使用 case 的帖子,所以我尝试将它实现到我的查询中。我的查询需要 where 中的条件。我知道我有语法问题,这就是我来这里的原因,希望有人能指出正确的方法来做到这一点。

谢谢你的时间

我目前的查询

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

最佳答案

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

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

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,您只需使用 END 关闭您的 CASE 语句,如下所示:

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

关于mysql - MYSQL where 子句中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18451207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com