简体   繁体   English

MySQL:一对多条件查询

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

I have a table with schema like this: 我有一个具有这样的架构的表:

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

date_done can be set both in the past, and in the future from current unix timestamp. date_done可以在过去以及将来从当前的unix时间戳设置。 I need to select all 'forgotten' clients, which don't have date_done set in future (in all his actions) and last his action is older than 604800 seconds (7 days). 我需要选择所有“忘记”的客户端,这些客户端在以后(在他的所有操作中)都未设置date_done,而他的操作最后已超过604800秒(7天)。 Client can have many actions. 客户可以执行许多操作。 And also, if it's possible, I need in the same query to select his last action (which is in past and more than 7 days old). 而且,如果可能的话,我需要在同一查询中选择他的上次操作(过去且已超过7天)。

How can it be done? 如何做呢?

One way to do it as 一种做到的方式

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 DEMO

In the demo I have added some data with future dates so that they can be ignored and just by getting data older than 7 days. 在演示中,我添加了一些带有未来日期的数据,因此可以通过使数据早于7天而忽略它们。 You can do group by in case there are repeated data in your table. 如果表中有重复的数据,则可以进行分组。

 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;

For the first part you want a query that has Where date_done < SysDate - 7 days and client_id not in (select id from clients_actions where date_done > SysDate (also converted to UNIX). This says I want all records whose date_done is older than 7 days ago, but that don't have any actions due in the future. 对于第一部分,您想要一个查询,其中date_done <SysDate-7天,而client_id不在其中(从client_actions中选择id,其中date_done> SysDate(也转换为UNIX)。这表示我希望date_done早于7天的所有记录以前,但是将来没有任何动作。

the MAX and group by client_id limit it to only the latest record of those selected by client_id. MAX和group by client_id将其限制为仅由client_id选择的最新记录。

The following query will get you the desired result. 以下查询将为您提供所需的结果。

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