我使用的是query like
select * from audittable where a_id IN (1,2,3,4,5,6,7,8);
对于每个ID,它返回5-6条记录。我想为每个ID获取倒数第二条记录。我可以在一条sql语句中做到这一点吗?
发布于 2013-06-06 13:22:03
尝试此查询
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-06 13:47:26
如果您的数据库包含DateCreated
或任何保存DateTime
的column
,比如为特定行插入数据时,则可以使用如下查询
select at1.* from audittable at1 where
datecreated in( select max(datecreated) from audittable at2
where
at1.id = at2.id
order by datecreated desc
);
您也可以使用LIMIT
函数。
希望你能理解并为你工作。
发布于 2014-01-23 02:12:50
在SQLite中,您有a_id和b列。对于每个a_id,您都会得到一组b。
SELECT MAX(b), *
FROM audittable
GROUP BY a_id
在这里,MAX帮助从每个组中获得最大b。
坏消息是,MySQL没有将MAX b与表的其他*列关联起来。但是它仍然可以在包含a_id和b列的简单表中使用!
https://stackoverflow.com/questions/16954096
复制相似问题