表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 |
+----+-------------+---------+
答案 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