首页 > 解决方案 > 按日期过滤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;

标签: mysqlsql

解决方案


您需要在聚合进行过滤,因为您的表达式具有聚合功能。因此,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;

推荐阅读