Delete records which have more than N entries
I have a table called history
,
which has three columns.
id
, value
, timestamp
Id
is not a primary key, but the pair (id, timestamp)
is unique.
What I would like to do is delete all the older records for a specific ID that exceed a certain limit.
For example if i have these values:
-1,value1,1
-1,value2,开发者_如何学Python2
-1,value3,3
-2,value4,4
-2,value5,5
-2,value6,6
And the limit is 2. After executing the statement i should get something like:
-1,value2,2
-1,value3,3
-2,value4,4
-2,value5,5
-2,value6,6
I think I have it (tried and works for the testcases i had), the answer is:
DELETE FROM history WHERE id = ?1 AND timestamp NOT in (SELECT sourcetime FROM history WHERE id =?1 ORDER BY timestamp DESC LIMIT ?2);
DELETE FROM ... WHERE timestamp < ...
Doesn't work ?
精彩评论