我知道这是一个常见的问题,但我还没有找到这个具体问题的答案:
我有两张table:
+--------------+ +-------------------------------+
| temp1 | | temp2 |
+----+---------+ +----+----+---------------------+
| id | name | | id | fk | ts |
+----+---------+ +----+--------------------------+
| 1 | first | | 1 | 1 | 2020-06-19 23:56:46 |
| 2 | second | | 2 | 1 | 2020-06-19 22:56:46 |
| 3 | third | | 3 | 2 | 2020-06-19 21:56:46 |
+----+---------+ | 4 | 2 | 2020-06-19 20:56:46 |
+----+--------------------------+
为了为temp1中的每个条目获取temp2中具有最新时间戳的对应条目,我正在运行以下查询:
SELECT
t1.id AS id,
t1.name AS name,
t2.ts AS ts
FROM
(temp2 t2
JOIN temp1 t1)
WHERE
t2.ts = (SELECT MAX(t3.ts)
FROM
temp2 t3
WHERE
t2.fk = t3.fk)
AND t2.fk = t1.id
这将导致:
+----+--------+---------------------+
| id | name | ts |
+----+------------------------------+
| 1 | first | 2020-06-19 23:56:46 |
| 2 | second | 2020-06-19 21:56:46 |
+----+------------------------------+
是否可以更改此查询以包含temp1中没有对应temp2值的行?
预期结果是:
+----+--------+---------------------+
| id | name | ts |
+----+------------------------------+
| 1 | first | 2020-06-19 23:56:46 |
| 2 | second | 2020-06-19 21:56:46 |
| 3 | third | NULL |
+----+------------------------------+
2条答案
按热度按时间pxyaymoc1#
使用窗口功能:
k7fdbhmy2#
最简单的方法是在
SELECT
列表:请看演示。
结果: