2014-09-26 129 views
4

我有一种情况,我只想限制表中的50行。如果用户在此之后插入新行,那么应删除第一行(首先插入),并插入新行,以便计数保持不变。 我知道我可以有一个rowid字段,在插入新记录时,我可以检查是否已经有50行,因此删除最小的rowid,然后插入新的记录。但只是想知道是否有更好的解决方案,以便我不必做3个数据库操作(1.查询#行,2.删除最小值,3.插入)SQLite中限制的行数

+0

你可能会插入后考虑触发和'ROWID <=(MAX(ROWID) - 50)删除所有行' – ssnobody 2014-09-26 01:38:18

+0

@ssnobody这将炸毁时'rowid's是不连续的。 – 2014-09-26 08:57:15

+0

如何查询行数或删除一些旧行,而无需数据库操作?根据定义,这些操作是对数据库的操作。 – 2014-09-26 08:57:58

回答

1

我知道一种方法可行,但有点难看。它依赖于精心构建的约束和种子数据库。为了简便起见,我只用五排,而不是50

create table test (
    row_num integer primary key 
    check ((round(row_num) = row_num) and (row_num between 1 and 5)), 
    other_columns char(1) not null default 'x', 
    row_timestamp timestamp 
    not null unique 
    default current_timestamp 
); 

表达round(row_num = row_num)保证你在ROW_NUM列整数。否则,SQLite会让你在那里插入1.54或'wibble'。

other_columns列只是您实际数据的占位符。

insert into test (row_num, row_timestamp) values 
(1, '2015-01-01 08:00:01'), 
(2, '2015-01-01 08:00:02'), 
(3, '2015-01-01 08:00:03'), 
(4, '2015-01-01 08:00:04'), 
(5, '2015-01-01 08:00:05'); 

实际的时间戳值并不代表什么。还没有,无论如何。像这样种子数据库意味着从现在开始,您只需执行更新语句。如果表格是空的,则必须处理不同的插入和更新逻辑。例如,您必须对行进行计数才能确定是插入还是更新。

create trigger update_timestamp 
after update on test 
for each row 
begin 
    update test 
    set row_timestamp = strftime('%Y-%m-%d %H:%M:%f', 'now') 
    where row_num = OLD.row_num; 
end; 

的 “update_timestamp” 触发使得SQLite的保持与第二(%f)级分中的时间戳。可能取决于底层操作系统是否支持小数精度。现在

create trigger no_deletes 
after delete on test 
for each row 
begin 
    -- There might be a more elegant way to prevent deletes. 
    -- This way just inserts exactly what a delete statement deletes. 
    insert into test (row_num, other_columns, row_timestamp) 
    values (OLD.row_num, OLD.other_columns, OLD.row_timestamp); 
end; 


可以更新数据。你更新自己的数据,这里只是占位符 other_columns,而SQLite负责处理剩下的数据。

update test 
set other_columns = 'b' 
where row_timestamp = (select min(row_timestamp) from test); 
select * from test order by row_timestamp desc; 
 
row_num  other_columns row_timestamp   
---------- ------------- ----------------------- 
1   b    2015-03-08 12:43:21.926 
5   x    2015-01-01 08:00:05  
4   x    2015-01-01 08:00:04  
3   x    2015-01-01 08:00:03  
2   x    2015-01-01 08:00:02