mySQL从所有者历史记录加入交易所有者

时间:2017-03-04 15:16:25

标签: mysql join

我有一个交易表,需要加入当时所有者所在的每笔交易:

交易(t)

+----+---------------------+---------+--------+
| id |        date         | details | itemID |
+----+---------------------+---------+--------+
|  1 | 2017-03-02 22:35:01 | info    |    123 |
|  2 | 2017-02-02 22:35:01 | info    |    123 |
|  3 | 2016-01-01 22:35:01 | info    |    123 |
+----+---------------------+---------+--------+

TransferHistory(th)

+----+---------------------+--------+------------+------------+
| id |        date         | itemID | newOwnerID | oldOwnerID |
+----+---------------------+--------+------------+------------+
|  1 | 2017-02-25 22:35:01 |    123 |        222 |        333 |
|  2 | 2017-02-02 20:35:01 |    123 |        333 |        444 |
|  3 | 2015-01-01 22:35:01 |    123 |        444 |        555 |
+----+---------------------+--------+------------+------------+

项目

+----+-------------+---------+
| id |   details   | ownerID |
+----+-------------+---------+
|123 | thing1      |     123 |
|  1 | other thing |     127 |
|  2 | big thing   |     129 |
+----+-------------+---------+

我可以通过 item 表加入当前所有者,但是如何根据 TransferHistory 表在每个交易日期加入所有者?

我要找的结果是:

+------+---------------------+-----------+----------+------------+
| t.id |       t.date        | t.details | t.itemID | th.ownerID |
+------+---------------------+-----------+----------+------------+
|    1 | 2017-03-02 22:35:01 | sale      |      123 |        222 |
|    2 | 2017-02-02 22:35:01 | something |      123 |        333 |
|    3 | 2016-01-01 22:35:01 | traded    |      123 |        444 |
+------+---------------------+-----------+----------+------------+

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法(在MySQL中)是一个相关的子查询:

select t.*,
       (select th.newOwnerId
        from transferhistory th
        where th.date <= t.date
        order by th.date desc
        limit 1
       ) as OwnerId_atdate
from transactions t;

注意:这假设转移历史记录包含第一个所有者的记录。