这是一个不止一次在这里提出的问题,但我无法找到我想要的东西。我正在寻找连接两个表,其中连接表由按日期时间排序的最后一个寄存器设置,直到这里一切正常。
我的麻烦开始在联接表上有两个以上的记录,让我给你看一个样本
table_a
-------
id
name
description
created
updated
table_b
-------
id
table_a_id
name
description
created
updated
我在开始时所做的是:
SELECT a.id, b.updated
FROM table_a AS a
LEFT JOIN (SELECT table_a_id, max (updated) as updated
FROM table_b GROUP BY table_a_id ) AS b
ON a.id = b.table_a_id
在此之前我收到了cols,a.id
和b.updated
。我需要完整的table_b
cols,但是当我尝试在查询中添加新的col时,Postgres告诉我需要将col添加到GROUP BY条件才能完成查询,结果是不是我想要的。
我正试图找到一种方法来获得此列表。
答案 0 :(得分:2)
您可以使用Postgres的distinct on
语法:
select a.id, b.*
from table_a as a left join
(select distinct on (table_a_id) table_a_id, . . .
from table_b
order by table_a_id, updated desc
) b
on a.id = b.table_a_id
. . .
的位置,您应该放入所需的列。
答案 1 :(得分:2)
尝试:
SELECT a.id, b.*
FROM table_a AS a
LEFT JOIN (SELECT t.*,
row_number() over (partition by table_a_id
order by updated desc) rn
FROM table_b t) AS b
ON a.id = b.table_a_id and b.rn=1
答案 2 :(得分:2)
DISTINCT ON
或是你的朋友。以下是正确语法的解决方案:
SELECT a.id, b.updated, b.col1, b.col2
FROM table_a as a
LEFT JOIN (
SELECT DISTINCT ON (table_a_id)
table_a_id, updated, col1, col2
FROM table_b
ORDER BY table_a_id, updated DESC
) b ON a.id = b.table_a_id;
或者,从table_b
获取整行:
SELECT a.id, b.*
FROM table_a as a
LEFT JOIN (
SELECT DISTINCT ON (table_a_id)
*
FROM table_b
ORDER BY table_a_id, updated DESC
) b ON a.id = b.table_a_id;
该技术的详细解释以及在这个密切相关的问题下的替代解决方案:
Select first row in each GROUP BY group?