繁体   English   中英

MySQL:一对多条件查询

[英]MySQL: query with condition on one-to-many table

我有一个具有这样的架构的表:

clients_actions
id | client_id | action | date_done
1  | 1         | ...    | 1394785392
2  | 2         | ...    | 1394786392
3  | 2         | ...    | 1394787392

date_done可以在过去以及将来从当前的unix时间戳设置。 我需要选择所有“忘记”的客户端,这些客户端在以后(在他的所有操作中)都未设置date_done,而他的操作最后已超过604800秒(7天)。 客户可以执行许多操作。 而且,如果可能的话,我需要在同一查询中选择他的上次操作(过去且已超过7天)。

如何做呢?

一种做到的方式

select * from clients_actions 
where from_unixtime(date_done) < date_sub(now(),INTERVAL 7 day) 
AND client_id
NOT IN
(
  select client_id from 
  clients_actions
  where from_unixtime(date_done) > now()
)
;

DEMO

在演示中,我添加了一些带有未来日期的数据,因此可以通过使数据早于7天而忽略它们。 如果表中有重复的数据,则可以进行分组。

 Select client_id, action, MAX(date_done) from clients_actions 
 WHERE date_done < (UNIX_TIMESTAMP(SYSDATE() - 7)
 AND id NOT IN (SELECT id FROM clients_actions 
                WHERE date_done > (UNIX_TIMESTAMP(SYSDATE()))
 GROUP BY client_id;

对于第一部分,您想要一个查询,其中date_done <SysDate-7天,而client_id不在其中(从client_actions中选择id,其中date_done> SysDate(也转换为UNIX)。这表示我希望date_done早于7天的所有记录以前,但是将来没有任何动作。

MAX和group by client_id将其限制为仅由client_id选择的最新记录。

以下查询将为您提供所需的结果。

SELECT *
FROM clients_actions ca
INNER JOIN
    (SELECT client_id, MAX(date_done) as date_done
    FROM clients_actions
    WHERE DATEDIFF(CURRENT_TIMESTAMP, FROM_UNIXTIME(date_done)) >= 7
    GROUP BY client_id) latest_date
ON ca.client_id = latest_date.client_id AND ca.date_done = latest_date.date_done;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM