mysql - 按日期过滤sql
问题描述
我有这个 sql 查询
select c.id, from_unixtime(max(cr.updated_at),'%Y-%m-%d') as last_activity
FROM clients as c
INNER JOIN clients_records as cr
ON c.id = cr.id_client
group by c.id
我需要过滤记录,因为我需要 last_activity 至少一年前的行
此查询不起作用:
select c.id, from_unixtime(max(cr.updated_at),'%Y-%m-%d') as last_activity
FROM clients as c
INNER JOIN clients_records as cr
ON c.id = cr.id_client
where from_unixtime(max(cr.updated_at),'%Y-%m-%d') < (SELECT DATE(NOW()-INTERVAL 1 YEAR))
group by c.id;
解决方案
您需要在聚合后进行过滤,因为您的表达式具有聚合功能。因此,having
,不是where
:
select c.id, from_unixtime(max(cr.updated_at),'%Y-%m-%d') as last_activity
from clients c join
clients_records cr
on c.id = cr.id_client
group by c.id
having from_unixtime(max(cr.updated_at), '%Y-%m-%d') < curdate() - interval 1 year;
我还简化了您的日期比较表达式。
having
注意:您可以在(虽然不是在)中使用列别名where
,因此进一步简化为:
having last_activity < curdate() - interval 1 year;
推荐阅读
- angular - 使用 @Storybook/addon-docs 显示模板的代码
- django - Django:如何将两个序列化器相互嵌套?
- javascript - 搜索栏返回所有列的结果
- python - 如何在 django/boostrap 中按类别过滤任务?
- python - 使用 openCV 从 numpy 数组生成视频
- laravel - Salesforce JWT 登录返回无效的客户凭证
- php - Jquery ajax表单提交即使返回false?
- swift - 测验结束后如何自动切换到另一个 viewController (SWIFT)
- spring-boot-chaos-monkey - 无法将“chaos.monkey.assaults”下的属性绑定到 de.codecentric.spring.boot.chaos.monkey.configuration.AssaultProperties
- javascript - 构建项目 React 时找不到本地 CSS 和 JS