MySQL date_add() 如何使用月份插入?

发布于 2024-08-11 09:26:43 字数 160 浏览 2 评论 0原文

大家好,我有这个 SQL,

SELECT DATE_ADD( '2009-'+ MONTH( NOW() ) +'-01' , INTERVAL -1 MONTH );

我无法让它工作,我在这里做错了什么?

坦克寻求帮助。

Hallo all, i have this SQL

SELECT DATE_ADD( '2009-'+ MONTH( NOW() ) +'-01' , INTERVAL -1 MONTH );

i can't get it to work, what i make wrong here?

tanks for help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

陌伤浅笑 2024-08-18 09:26:43
SELECT CONCAT_WS('-', '2009', MONTH(NOW()), '01') - INTERVAL 1 MONTH
SELECT CONCAT_WS('-', '2009', MONTH(NOW()), '01') - INTERVAL 1 MONTH
够运 2024-08-18 09:26:43

这是行不通的日期串联。它将字符串转换为数字,因此得到 2009+11+-1 = 2019,但无法转换为日期。

您可以使用 last_day 函数来获取当月的最后一天,添加一天以获取下个月的第二天,然后减去两个月以获取该月的第一天,而不是连接字符串中的日期。上个月:

select last_day(now()) + interval 1 day - interval 2 month;

It's the concatenation of the date that doesn't work. It converts the strings to numbers, so you get 2009+11+-1 = 2019, which then fails to convert to a date.

Instead of concatenating a date from strings, you can use the last_day function to get the last day of the current month, add one day to get to the next day of the next month, then subtract two months to get to the first day of the previous month:

select last_day(now()) + interval 1 day - interval 2 month;
我不会写诗 2024-08-18 09:26:43

Plus是算术运算符,必​​须使用concat。

SELECT DATE_ADD( concat('2009-',MONTH(NOW()),'-01') , INTERVAL -1 MONTH )

或更好

select date(now()) -  interval day(NOW())-1 day - interval 1 month;

(这也适用于 2010 年)

Plus is an arithmetical operator, you have to use concat.

SELECT DATE_ADD( concat('2009-',MONTH(NOW()),'-01') , INTERVAL -1 MONTH )

or better

select date(now()) -  interval day(NOW())-1 day - interval 1 month;

(this will also work in 2010)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文