如何在不使用子查询的情况下使用max(time)获得适当的列?

时间:2019-03-20 05:23:19

标签: mysql sql

我有下表和值:

mysql> select * from test;
+------+-------+------------+
| id   | link  | time       |
+------+-------+------------+
|    1 | link1 | 2019-03-04 |
|    1 | link2 | 2019-03-05 |
|    1 | link3 | 2019-03-06 |
|    2 | link3 | 2019-03-07 |
|    2 | link4 | 2019-03-07 |
+------+-------+------------+

我想在时间值为max时获取 id link 列, 我可以使用子查询来完成它:

mysql> select B.id, B.link from test B, (select id, max(time) as time 
       from test group by id) A where A.time = B.time and A.id = B.id;
+------+-------+
| id   | link  |
+------+-------+
|    1 | link3 |
|    2 | link3 |
|    2 | link4 |
+------+-------+

我不知道如何不使用子查询来完成它,任何建议将不胜感激!

另一个:

我想得到:

+------+-------+
| id   | link  |
+------+-------+
|    1 | link3 |
|    2 | link3 |
+------+-------+

OR

+------+-------+
| id   | link  |
+------+-------+
|    1 | link3 |
|    2 | link4 |
+------+-------+

我该怎么办?

3 个答案:

答案 0 :(得分:1)

使用相关子查询

select a.* from test a
where (a.time,a.link) in(select max(time),max(link) from test b where a.id=b.id)

如果您的版本是mysql 8.0+ 然后使用row_number()

select * from (
select a.*,row_number()over(partition by a.id order by a.time desc) rn
 from test a
) b where b.rn=1

答案 1 :(得分:0)

请尝试这个。

  Select * from (select A.id,A.time,A.link, ROW_NUMBER() OVER(partition by A.id order by A.time desc)As row_num from @tbl  A )AS AA Where AA.row_num =1  

OR

select A.id,A.time,A.link from test  A
    order by A.time desc
    limit 1

答案 2 :(得分:0)

您可以使用limit或top

限制(mysql):

Select id,max(time),link  from test group by id,link  order by time desc limit 1

top(mssql):

 Select top 1 id,max(time),link  from test group by id,link  order by time desc