简体   繁体   中英

How do I do a MySQL JOIN on conditions based on mathematical operations across two tables?

I have two tables in a CRM application that I am trying to build.

"Contacts" Table:

id Name ContactFrequency (in days)
1 John 7
2 Pete 30

"Events" Table:

id Contacts_id Description Unix_Timestamp
1 1 Sent John an email 1609667504
2 1 Gave John a call 1609645455
1 2 Sent Pete a letterl 1609666755

The "ContactFrequency" is how often I should call that client to stay in touch. Each entry in Events is a call log with a UNIX timestamp. I want to generate a list of clients who need to be called in the next X number of days (or whose next contacts have already passed and are overdue), such as the following (timestamps are completely arbitrary in my examples):

Client Next Contact Due on (Timestamp)(Ordered by this column)
Pete 1609645352
John 1609634342

How would I do this with a query? I can't wrap my head around it.

Formally:

SELECT Contacts.Name Client, 
       COALESCE(FROM_UNIXTIME(MAX(Events.Unix_Timestamp)) + INTERVAL Contacts.ContactFrequency DAY, CURRENT_TIMESTAMP) NextContactDueOn
FROM Contacts
LEFT JOIN Events ON Contacts.id = Events.Contacts_id
GROUP BY Client
ORDER BY NextContactDueOn DESC

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