【问题标题】:How to get last records with conditions from SQLite?如何从 SQLite 获取具有条件的最后记录?
【发布时间】:2017-11-14 13:02:17
【问题描述】:

我需要从 SQLite 获取最后一条记录,但有一些条件。假设我有这张表

id         course
1           math 
2           english      
3           math       
4           english   
5           chemistry 

我需要返回 ID 为 3、4、5 的记录,因为对于 math,id:3 是最后一个(最新)记录,对于 english,id:4 是最后一个(最新) 记录等等..

我不知道如何将它们分组,然后选择最新的记录等等..

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    你似乎想要:

    select max(id) as id, course
    from t
    group by course;
    

    【讨论】:

      【解决方案2】:

      SQLite 有一个 rowid,您可以像这样查询它:

      select *   
      from Table1 t
      where exists (
        select 1
        from Table1 ti  
        where t.course = ti.course
        group by ti.course
        having t.rowid = max(ti.rowid);    -- filtering rows that are newest rows in table
        );
      

      SQLite Fiddle Demo

      样本数据:

      | id |    course |      ... hidden rowid |
      |----+-----------|      ... -------------|
      |  1 |      math |      ...            1 |
      |  2 |   english |      ...            2 |
      |  3 |      math |      ...            3 |
      |  4 |   english |      ...            4 |
      |  5 | chemistry |      ...            5 |
      |  8 |      test |      ...            6 |
      |  7 |      test |      ...            7 |
      

      结果:

      | id |    course |      ... hidden rowid |
      |----+-----------|      ... -------------|
      |  3 |      math |      ...            3 |
      |  4 |   english |      ...            4 |
      |  5 | chemistry |      ...            5 |
      |  7 |      test |      ...            7 |
      

      【讨论】:

        猜你喜欢
        • 2012-04-11
        • 1970-01-01
        • 2012-01-23
        • 1970-01-01
        • 2023-01-17
        • 2012-02-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多