簡體   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