简体   繁体   English

动态,在 mysql 中的 Where 子句中使用 Case 语句

[英]Dynamic , Using a Case Statement in a Where Clause in mysql

I am stucked at a dynamic where clause inside case statement.我被卡在 case 语句中的动态 where 子句中。

WHAT I NEED我需要的

When i used this当我用这个

SELECT col1,col2,col3
FROM Recharge r INNER join ft f ON f.date=r.date
WHERE f.Date LIKE 
CASE WHEN f.Date  BETWEEN (last_day(curdate() - interval 1 month) + interval 1 day) AND last_day(curdate())  
                  THEN f.Date  ELSE f.date between subdate(curdate(),interval 1 month) and (last_day(curdate() - interval 1 month)) END
ORDER BY f.id desc;

The syntax is wrong but when instead it '2022-04%'.语法错误,但改为“2022-04%”。

SELECT col1,col2,col3

FROM Recharge r INNER join ft f ON f.date=r.date
WHERE f.Date LIKE 
CASE WHEN f.Date  BETWEEN (last_day(curdate() - interval 1 month) + interval 1 day) AND last_day(curdate())  
                  THEN f.Date  ELSE '2022-04%' END
ORDER BY f.id desc;

It is correct but i want to change dynamically.how can i do it.这是正确的,但我想动态改变。我该怎么做。 I mean that when i run the query include date of 1-4-2022 to 30-4-2022.我的意思是,当我运行查询时,包括 1-4-2022 到 30-4-2022 的日期。 The snapshot my database include data of yesterday in the begin of month i have the issue.我的数据库快照包括月初的昨天数据我有问题。

A case statement can only return a value and not a range. case 语句只能返回一个值,不能返回一个范围。 If I understand rightly it is only the start date which changes so we only need to decide the start date in the case statement.如果我理解正确的话,只是开始日期发生了变化,所以我们只需要在案例陈述中决定开始日期。 If the end date also changes we will need a second case statement.如果结束日期也发生变化,我们将需要第二份案例陈述。 However it looks like a simple test will return the same results然而,看起来一个简单的测试会返回相同的结果

SELECT col1,col2,col3
FROM Recharge r INNER join ft f ON f.date=r.date
WHERE f.Date BETWEEN
curdate() - interval 1 month
  AND
last_day(curdate())
ORDER BY f.id desc;

Re-reading your explanation I think that you really want重读你的解释我认为你真的想要

SELECT col1,col2,col3
FROM Recharge r INNER join ft f ON f.date=r.date
WHERE month(f.date) = month(curdate() - interval 1 day)
AND year(f.date) = year(curdate() - interval 1 day )
ORDER BY f.id desc;

db<>fiddle here db<> 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM