[英]Set MONTH in MYSQL based on another DATETIME value in the same row
I have two date fields in each row of the same table.我在同一张表的每一行中有两个日期字段。 I'm trying to figure out how to update just the MONTH of one date based on whether it is greater or less than the other date.我试图弄清楚如何根据一个日期的 MONTH 是大于还是小于另一个日期来更新它。
Here's what I need to execute: IF the second date is GREATER THAN the first date, then set the MONTH of the first date equal to the MONTH of the second date.这是我需要执行的操作:如果第二个日期大于第一个日期,则将第一个日期的 MONTH 设置为等于第二个日期的 MONTH。
So if the first date is '2021-03-16' and the second date is '2021-05-01', I want to update the first date to equal '2021-05-16'.因此,如果第一个日期是“2021-03-16”,第二个日期是“2021-05-01”,我想将第一个日期更新为“2021-05-16”。
Or, for a less verbose description, how do I transform this...或者,对于一个不太冗长的描述,我该如何转换这个......
Data set:数据集:
id date_1 date_2
1 2021-03-16 2021-05-01
2 2021-03-16 2021-02-01
...into this... ……进入这个……
id date_1 date_2
1 2021-05-16 2021-05-01
2 2021-03-16 2021-02-01
Any suggestions on the correct method/syntax to do this would be greatly appreciated.任何有关正确方法/语法的建议将不胜感激。
UPDATE table
SET first_date = CONCAT_WS('-', YEAR(first_date),
MONTH(GREATEST(first_date, second_date)),
DAY(first_date));
You can add to date_1
as many months as is the difference of the months in the 2 dates:您可以在date_1
中添加与 2 个日期中月份的差值一样多的月份:
UPDATE tablename
SET date_1 = date_1 + INTERVAL MONTH(date_2) - MONTH(date_1) month
WHERE date_1 < date_2
See the demo .请参阅演示。
Results:结果:
id ID | date_1日期_1 | date_2日期_2 |
---|---|---|
1 1 | 2021-05-16 2021-05-16 | 2021-05-01 2021-05-01 |
2 2 | 2021-03-16 2021-03-16 | 2021-02-01 2021-02-01 |
Note, that your requirement may fail in case of dates like date_1 = '2021-03-31'
and date_2 = '2021-04-30'
because this '2021-04-31'
is not a valid date.请注意,如果date_1 = '2021-03-31'
和date_2 = '2021-04-30'
这样的日期,您的要求可能会失败,因为此'2021-04-31'
不是有效日期。
But the above query will work by changing the day also.但是上面的查询也可以通过更改日期来工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.