这是一个简单的问题。
我应该基于时间戳字段在某个表中最多包含400行,因此旧的行将被自动删除。对于这里,我们假设它是3。
该表具有多个字段,但是时间戳在这里很重要。
即使我成功了,由于某种原因,它也使我最大程度地增加了其他项目,因此我只是对其进行了相应的调整。这意味着我得到了3个项目,而不是3个。
private const val MAX_ITEMS = 3 private val TIMESTAMP_FIELD = "timestamp" private val DELETE_FROM_CALL_LOG_TILL_TRIGGER = String.format( "CREATE TRIGGER %1\$s INSERT ON %2\$s WHEN (select count(*) from %2\$s)>%3\$s BEGIN DELETE FROM %2\$s WHERE %2\$s._id IN " + "(SELECT %2\$s._id FROM %2\$s ORDER BY %2\$s.$TIMESTAMP_FIELD DESC LIMIT %3\$d, -1); END;" , "delete_till_reached_max", TABLE_NAME, MAX_ITEMS - 1)
我试过了 :
WHEN
LIMIT %3\$d, -1
LIMIT -1 OFFSET %3\$d
MAX_ITEMS - 1
MAX_ITEMS
BEFORE | AFTER
BEFORE
这应该工作:
private const val MAX_ITEMS = 3 private val TIMESTAMP_FIELD = "timestamp" private val DELETE_FROM_CALL_LOG_TILL_TRIGGER = String.format( "CREATE TRIGGER %1\$s AFTER INSERT ON %2\$s FOR EACH ROW BEGIN DELETE FROM %2\$s WHERE _id = (SELECT _id FROM %2\$s ORDER BY %4\$s DESC LIMIT 1 OFFSET %3\$s); END;" , "delete_till_reached_max", TABLE_NAME, MAX_ITEMS, TIMESTAMP_FIELD)
一旦表中有400行,您就可以像这样调用触发器trg_keep_rowcount_constant并将其GROUP BY null HAVING COUNT(*) > %3\$s从代码中删除。
trg_keep_rowcount_constant
GROUP BY null HAVING COUNT(*) > %3\$s
演示:https://dbfiddle.uk/?rdbms = sqlite_3.27&fiddle = ea3867e20e85927a2de047908771f4f1