按日期过滤SQL

时间:2018-07-09 14:09:06

标签: 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;

1 个答案:

答案 0 :(得分:0)

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