如何从SQLite获取条件的最后记录?

时间:2017-11-14 13:02:17

标签: sql sqlite

我需要从SQLite获取最后的记录,但有一些条件..让我们说我有这张表

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

我需要返回ID 3,4,5的记录,因为math id:3是english id $.ajax({ type: "GET", crossDomain: true, beforeSend: function (request) { request.setRequestHeader("Authorization", "Bearer " +($("#accesstoken").val())); }, url: myJSonServer + encodeURI(operation), dataType: 'jsonp', cache: false, success: callback, error: function (jqXhr, textStatus, errorThrown) { alert(textStatus + ": " + errorThrown); } }); 的最后一条(最新)记录}:4是最后一条(最新的)记录,依此类推......

我不知道如何对它们进行分组,然后选择最新的记录等等。

2 个答案:

答案 0 :(得分:2)

你似乎想要:

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

答案 1 :(得分:0)

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 |