简体   繁体   中英

How do I write a Query to join two tables based on minimum absolute time difference?

I need help writing a MySQL query to do a matching with the tables below. So far my query looks like this:

SELECT event.id, event.eventid, upload.uploadid
FROM event
LEFT JOIN upload
ON(event.id = upload.id and event.timestamp <= upload.timestamp);

The second condition in my join, event.timestamp <= upload.timestamp , is a placeholder until I can figure out a boolean expression (or something else) to get the desired result. I'm lost on how to write a statement to join based on minimum absolute time difference. The tables have the following structure:

Event table

id eventid timestamp
u1 event1 2020-01-01 01:30:00
u1 event2 2020-01-01 01:45:00
u2 event1 2020-01-01 05:30:00
u2 event2 2020-01-01 05:39:00

Upload table

id uploadid timestamp
u1 upload1 2020-01-01 01:30:00
u1 upload2 2020-01-01 02:30:00
u2 upload1 2020-01-01 05:30:00
u2 upload2 2020-01-01 05:35:00

The query needs to match every event in the event table to the closest upload from that respective user.

The desired result of the query is:

u1 event1 upload1
u1 event2 upload1
u2 event1 upload1
u2 event2 upload2

EDIT: The following query produced the the desired result:

SELECT e.id, e.eventid, 
        (SELECT u.uploadid
        FROM upload u
        WHERE (u.id = e.id and u.timestamp < e.timestamp)
        ORDER BY ABS(TIMESTAMPDIFF(second, u.timestamp, e.timestamp))
        LIMIT 1) 
FROM event e;

If you only want the uploadid , then I would suggest a correlated subquery:

SELECT e.*,
       (SELECT u.uploadid
        FROM upload u
        WHERE u.id = e.id
        ORDER BY ABS(TIMESTAMPDIFF(second, e.timestamp, u.timestamp))
       ) as uploadid
FROM event e;

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