我使用像獲得最後,但每一行對應一個ID
select * from audittable where a_id IN (1,2,3,4,5,6,7,8);
查詢每一個ID其返回5-6的記錄。我想獲得每個ID的最後一條記錄。 我可以在一個sql語句中做到這一點。
我使用像獲得最後,但每一行對應一個ID
select * from audittable where a_id IN (1,2,3,4,5,6,7,8);
查詢每一個ID其返回5-6的記錄。我想獲得每個ID的最後一條記錄。 我可以在一個sql語句中做到這一點。
如果你的數據庫是有DateCreated
或任何column
嘗試此查詢
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;
您在其中保存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
函數。
希望你理解併爲你工作。
在SQLite中,您有列a_id和b。對於每個a_id,你會得到一組b。讓你想 以獲得最新的/最高(最大的ROW_ID,日期或其他自然增加指數換算)爲B的
SELECT MAX(b), *
FROM audittable
GROUP BY a_id
這裏MAX幫助,以獲得最大b從每一組中。
不好的消息,MySQL不會將MAX b與表中的其他*列相關聯。但它仍然可以用於a_id和b列的簡單表格!
你有沒有created_date或其他id列?或者你可以發佈你的表格腳本,所以我們可以幫你 – vikas
看到這裏http://stackoverflow.com/questions/6841605/get-top-1-row-of-each-group – PSR
更好地創建一個虛擬列a_id ,然後通過該列編寫查詢。 –