mysql 查询最新记录,MySQL查询 - 今天和最近30天之间的记录

I want to return all records that were added to the database within the last 30 days. I need to convert the date to mm/dd/yy because of display purposes.

create_date between DATE_FORMAT(curdate(),'%m/%d/%Y') AND (DATE_FORMAT(curdate() - interval 30 day,'%m/%d/%Y'))

My statement fails to limit the records to the last 30 days - it selects all the records.

Can anyone point me in the right direction? It feels like I am close.

Thanks and have a great week.

解决方案

You need to apply DATE_FORMAT in the SELECT clause, not the WHERE clause:

SELECT DATE_FORMAT(create_date, '%m/%d/%Y')

FROM mytable

WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()

Also note that CURDATE() returns only the DATE portion of the date, so if you store create_date as a DATETIME with the time portion filled, this query will not select the today's records.

In this case, you'll need to use NOW instead:

SELECT DATE_FORMAT(create_date, '%m/%d/%Y')

FROM mytable

WHERE create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值