mysql interval weekday,Mysql DATE_SUB(NOW(),INTERVAL 1天)24小时或工作日?

本文介绍了一种使用SQL查询来精确统计过去24小时内注册用户的高效方法。通过对比用户注册时间与当前日期之间的关系,利用BETWEEN操作符确定了有效的日期范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I am trying to get the totaal amount of registerd users per day. At the moment i am using this

$sql = "SELECT name, email FROM users WHERE DATE_SUB(NOW(), INTERVAL 1 DAY) < lastModified"

but i am not sure if this works per day or per 24 hours?

For example, a user who registered 22 hours ago shouldn't be returned i just like the user of today(=Tuesday)

解决方案

lastModified is, presumably, a datetime. To convert this into a date you can simply wrap it in DATE() i.e. DATE(lastModified). DATE() returns the date part of a datetime value which is effectively 00:00 on that day.

SELECT

name,

email

FROM users

WHERE DATE(lastModified) = DATE( DATE_SUB( NOW() , INTERVAL 1 DAY ) )

Using this to match a WHERE though would be inefficient as all rows would require DATE applied to them and so it would probably scan the whole table. It is more efficient to compare lastModified to the upper and lower bounds you are looking for, in this case >= 00:00 on SUBDATE(NOW(),INTERVAL 1 DAY) and < 00:00 on NOW()

Therefore you can use BETWEEN to make your select giving the following.

SELECT

name,

email

FROM users

WHERE lastModified

BETWEEN DATE( DATE_SUB( NOW() , INTERVAL 1 DAY ) )

AND DATE ( NOW() )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值