联接两个带有最新外键输入的表

时间:2019-06-05 15:40:57

标签: mysql greatest-n-per-group

  • 我有一个设备表(A)和另一个具有设备详细信息的表(B)。
  • 表B对于表A的每个设备ID都有多个条目。
  • 我需要从表A中获取所有设备以及从表B中获取其最新条目。

表A:

+----+--------+---------+
| id1| name   | Details |
+----+--------+---------+
| 1  | name1  | text1   |
| 2  | name2  | text2   |
| 3  | name3  | text3   |
| 4  | name4  | text4   |
+----+--------+---------+

表B:

+----+-------------+---------+
| id2|  device_id  | battery |
+----+-------------+---------+
| 1  | 1           | 20%     |
| 2  | 1           | 40%     |
| 3  | 1           | 30%     |
| 4  | 2           | 15%     |
| 5  | 2           | 75%     |
| 6  | 3           | 90%     |
+----+-------------+---------+

预期结果:

+----+-------------+---------+
| id1|  device_id  | battery |
+----+-------------+---------+
| 1  | 1           | 30%     |
| 2  | 2           | 75%     |
| 3  | 3           | 90%     |
| 4  | NULL        | NULL    |
+----+-------------+---------+

1 个答案:

答案 0 :(得分:0)

我得到了答案!

SELECT a.*, b1.*
FROM table_A a
LEFT JOIN table_B b1 ON (a.id = b1.device_id)
LEFT JOIN table_B b2 ON (a.id = b2.device_id AND 
    (b1.date < b2.date OR b1.date = b2.date AND b1.id < b2.id))
WHERE b2.id IS NULL
ORDER BY a.id