我有以下MySql表:
id|time|depth
id和time是主键。我需要一个查询来选择一行,当深度在最大时间不为0。理想情况下,我甚至需要最大值之前的行。
我来举个例子。这个表可以是这样的:
id time depth
----------------------------
1 0 0
1 10 1
1 20 2
2 0 0
2 10 1
在这种情况下,它应该返回:
id time depth
----------------------------
1 20 2
2 10 1
Thank you so much
与子查询连接是一种方法。
SELECT a.id, a.time, a.depth FROM Table1 a
INNER JOIN
(SELECT id, max(`time`) as mt FROM Table1 WHERE `depth` != 0 GROUP by id) as b
ON a.id = b.id and a.time = b.mt
试试这个:
select id,max(time) from test1 where depth<>0 group by id