选择mysql中每个ID的第二行

选择mysql中每个ID的第二行,mysql,sql,select,group-by,Mysql,Sql,Select,Group By,我有一张桌子: ID | time 1 | 300 1 | 100 1 | 200 2 | 200 2 | 500 我想为每一个身份证拿到第二排 我知道我可以拿到第一排 但我不知道如何获得每一个身份证的第二排。 我知道mysql中的limit和offset子句,但不知道如何在这里使用它们。 我怎么做 EDIT : Actually, time is not ordered. I forgot to specify that. I have made an edit in the table.

我有一张桌子:

ID | time
1 | 300
1 | 100
1 | 200
2 | 200
2 | 500
我想为每一个身份证拿到第二排 我知道我可以拿到第一排

但我不知道如何获得每一个身份证的第二排。 我知道mysql中的limit和offset子句,但不知道如何在这里使用它们。 我怎么做

EDIT : Actually, time is not ordered. I forgot to specify that. I have made an edit in the table.
请注意,任何结果少于n的条目都将被忽略

SELECT ID, MAX(time) time
FROM
    (
        select ID, Time
        from    TableName a
        where 
        (
            select count(*) 
            from TableName as f
            where f.ID = a.ID and f.time <= a.time
        ) <= 2
    ) s
GROUP BY ID

我只是想知道怎么做,但我没办法解决,也许你能解决。如有任何建议,请纠正我的疑问

首先,选择每个id的第一行

                  SELECT min(id) id 
                 FROM TableName t2
                 group by id
然后选择不在第一个查询中的minid以选择第二行minid

那样

      SELECT  min(id) id ,time
      FROM TableName 
      WHERE id NOT IN    (
                          SELECT min(id) id 
                          FROM TableName 
                          GROUP BY id
                         )
      GROUP BY id
**正如我所说,这只是建议。它返回0个值。如果你修复了它,请让我编辑我的帖子以获得帮助


您不能对现有的表执行此操作。你可以大胆尝试:

select id, time
from (select id, time
      from t
      group by t
     ) t
where not exists (select 1 from t t2 where t2.id = t.id and t2.time = t.time)
group by id
也就是说,尝试过滤掉第一行

这是不可能的,因为表本身是无序的,所以表中没有真正的秒定义。这使SQL引擎有机会在处理过程中按照自己认为合适的方式重新排列行,这可以带来巨大的性能提升

即使是您正在使用的构造:

select id, time
from t
group by id
不保证从第一行返回时间。这是MySQL的一个错误特性,称为隐藏列。它实际上只适用于所有值都相同的情况。我承认,在实践中,它似乎从第一行获得了值,但您不能保证这一点

最好的解决方案可能是将数据选择到具有自动递增列的新表中:

create table newtable (
    autoid int auto_increment,
    id int,
    time int
);

insert into newtable(id, time)
    select id, time from t;

实际上,这可能会保持与原始表相同的顺序,然后可以使用autoid获取第二行。不过,我想强调的是,在实践中存在的问题。无法保证这些值的顺序正确,但它们可能会正确。

选择ID,时间从T组按ID排序;无论如何都不推荐。我已经做了一次编辑,因为时间没有安排。请根据这一点给出答案。假设你想要按时间排序的结果,那么给出的答案没有区别!
select id, time
from t
group by id
create table newtable (
    autoid int auto_increment,
    id int,
    time int
);

insert into newtable(id, time)
    select id, time from t;