简体   繁体   English

如何根据最小绝对时间差编写查询以连接两个表?

[英]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.我需要帮助编写 MySQL 查询来匹配下表。 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.我的加入中的第二个条件event.timestamp <= upload.timestamp是一个占位符,直到我可以找出 boolean 表达式(或其他表达式)以获得所需的结果。 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 ID eventid事件标识 timestamp时间戳
u1 u1 event1事件1 2020-01-01 01:30:00 2020-01-01 01:30:00
u1 u1 event2事件2 2020-01-01 01:45:00 2020-01-01 01:45:00
u2 u2 event1事件1 2020-01-01 05:30:00 2020-01-01 05:30:00
u2 u2 event2事件2 2020-01-01 05:39:00 2020-01-01 05:39:00

Upload table上传表格

id ID uploadid上传id timestamp时间戳
u1 u1 upload1上传1 2020-01-01 01:30:00 2020-01-01 01:30:00
u1 u1 upload2上传2 2020-01-01 02:30:00 2020-01-01 02:30:00
u2 u2 upload1上传1 2020-01-01 05:30:00 2020-01-01 05:30:00
u2 u2 upload2上传2 2020-01-01 05:35:00 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:如果您只想要uploadid ,那么我建议使用相关子查询:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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