mysql - 连接两个表并进行时间比较

标签 mysql database-design join

设置

我有两张 table 想要加入。

表1

id, movement_time, coordinate_x, coordinate_y
123, 2014-06-08 08:01:24, 1, 10
123, 2014-06-08 08:01:54, 1, 11
321, 2014-06-08 08:01:30, 99, 2
...

表2

communication_time, from_id, to_id
2014-06-08 08:01:29, 123, 321
...

在这两个表中,time 列都是 DATETIME 类型,因此我可以比较时间。

这两个时间可能不一致。例如,如上例所示,用户 123table1 中的移动时间可能不会出现在 table2 中,反之亦然。

问题

我想要做的是连接这两个表,这样

1) 对于table2中的每条记录,我想找到from_id对应的coefficient_xcoefficient_yto_id 分别。

2)由于两个时间列没有对齐,我很可能找不到准确的时间匹配。所以我使用以下规则:

- For each record in `table2`, I take its `time` and `from_id` (or `to_id`) as given, 

- Then, in `table1`, find the most recent record for the same `id`. The `movement_time` <= `communication_time`

- Attach the coordinates to the `table2` record

如何使用MySQL来完成这个任务?

谢谢,

最佳答案

让我们首先看一个案例,如果 2014-06-08 08:01:29, 123:

SELECT t1.coordinate_x, t1.coordinate_y
    FROM table1 AS t1
    WHERE t1.movement_time <= '2014-06-08 08:01:29'
      AND t1.id = 123
    ORDER BY t1.movement_time DESC
    LIMIT 1;

这将受益于 INDEX(id, moving_time)

这对于那种情况正确吗?假设确实如此,让我们继续实际使用 table2:

SELECT t2.communication_time,
       t1a.coordinate_x AS from_x,
       t1a.coordinate_y AS from_y
    FROM table2 AS t2
    JOIN (
        SELECT t1.coordinate_x, t1.coordinate_y
            FROM table1 AS t1
            WHERE t1.movement_time <= t2.communication_time
              AND t1.id = t2.from_id
            ORDER BY t1.movement_time DESC
            LIMIT 1;
         ) t1a;

它仍然“正常”工作吗?

我是否应该将其作为“读者练习”以获取 to_id 的坐标? (提示:另一个加入。)

关于mysql - 连接两个表并进行时间比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31167338/

相关文章:

mysql - 如何根据第一个表的列值从两个表中获取行信息

URL 中的 php 标题

mysql - Rails SQL 创建表语法

sql - 有限制的多对多关系的数据库设计

php - 插入订单的总值(value),还是每次都计算?

MySQL - 按月计数(包括丢失的记录)

mysql - 从 MySQL 查询生成 Mongo 查询

php - 嵌套评论背后的算法是什么?

arrays - 如何连接以逗号分隔的命名范围的返回值

mysql - 在 JOIN 查询中将列设置为 null 或为空