0

我正在使用类似的查询

select * from audittable where a_id IN (1,2,3,4,5,6,7,8);

对于每个 ID,它返回 5-6 条记录。我想为每个 ID 获取最后一条记录。我可以在一个 sql 语句中执行此操作吗?

4

3 回答 3

0

如果您的数据库具有 DateCreatedcolumn您正在保存的任何内容,DateTime例如当您的数据插入特定行时,那么您可以使用类似查询

select at1.* from audittable at1 where 
datecreated in( select max(datecreated) from audittable at2
where 
at1.id = at2.id
order by datecreated desc
);

您也可以使用LIMIT函数。

希望您理解并为您工作。

于 2013-06-06T05:47:25.527 回答
0

试试这个查询

SELECT 
   * 
FROM 
   (SELECT 
       @rn:=if(@prv=a_id, @rn+1, 1) as rId,
       @prv:=a_id as a_id,
       ---Remaining columns
   FROM 
       audittable
   JOIN
       (SELECT @rn:=0, @prv:=0) t
   WHERE
       a_id IN (1,2,3,4,5,6,7,8)
   ORDER BY 
       a_id, <column> desc)tmp --Replace column with the column with which you will determine it is the last record
WHERE 
   rId=1;
于 2013-06-06T05:22:02.610 回答
0

在 SQLite 中,您有 a_id 和 b 列。对于每个 a_id,您都会得到一组 b。让您想要获取 b 中的最新/最高(就 row_id、日期或其他自然增加的索引而言的最大值)

SELECT MAX(b), *
FROM audittable
GROUP BY a_id

这里MAX有助于从每个组中获得最大b 。

MySQL 没有将 MAX b 与表的其他 *-columns 关联的坏消息。但它仍然可以用于具有 a_id 和 b 列的简单表的情况!

于 2014-01-22T18:12:50.480 回答