我有一个具有这种结构的table_A:
|- id_a primary key
|- id_b references table_B(id_b)
|- timestamp
|- varchar_column
我需要做一个连接在table_B上的查询,它必须在table_A.id_b上是不同的,但它必须返回其他列(不仅是不同的列);我还需要为每个不同的table_a.id_b获取具有最大时间戳的记录。 我确实喜欢两种方式,但它们都返回错误:
SELECT DISTINCT(table_A.id_b) FROM table_A INNER JOIN table_B on table_A.id_b = table_B.id_b ORDER BY table_A.timestamp DESC
和这一个:
SELECT * FROM table_A INNER JOIN table_B on table_A.id_b = table_B.id_b ORDER BY table_A.timestamp DESC GROUP BY table_A.id_b
答案 0 :(得分:1)
您可以在table_a上使用内部联接来获取id_b和max(时间戳)并加入其余表
select *
from table_A a
Inner join (
select id_b, max(timestamp) my_time
from table_A
group by id_b
) t on t.id_b = a.id_b and t.my_time = a.timestamp
inner join table_B on a.id_b = table_B.id_b
ORDER BY a.timestamp DESC