简体   繁体   中英

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. 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). 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).

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

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. 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.

the MAX and group by client_id limit it to only the latest record of those selected by 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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