SQL获取与max()关联的列值

时间:2013-03-04 06:28:21

标签: sql

我有下表

ID     Version         
---    ----------    
123      1           
124      2           
125      3           
126      4           
127      5           
128      6    

现在我需要获取版本号最大的ID值

我能做的是

select ID from tbl where version = (select max(version) from tbl)

我不想使用它,因为我需要在另一个查询中的连接中使用此部分,我不想让事情进一步复杂化。

2 个答案:

答案 0 :(得分:1)

您可以使用select FIRST()

SELECT FIRST(id) FROM tbl ORDER BY Version DESC

或使用 LIMIT 1 选项限制数字结果:

SELECT id FROM tbl ORDER BY Version DESC LIMIT 1

答案 1 :(得分:0)

你提到你在连接中需要这个,所以这样的事情应该这样做

select *
from table_1 as t1
  join (
      select id, 
             row_number() over (order by version desc) as rn
      from table_2
  ) as t2 on t1.id = t2.id and t2.rn = 1

(这是ANSI SQL,因为你没有提到DBMS - 但应该适用于大多数现代DBMS)

相关问题