有几种方法可以将表限制为 100 行。(为简洁起见,下面的代码中有 5 行。)在 SQLite 版本 3.7.9 中测试。
所有这些代码都依赖于 SQLite 处理数据类型声明的方式中的一种怪癖。(无论如何,这对我来说似乎很古怪。)SQLite 允许您将诸如 3.14159 和“wibble”之类的废话插入到一个裸整数列中。但它允许您仅将整数插入声明的列中integer primary key
或integer primary key autoincrement
。
FOREIGN KEY 约束
对有效 id 编号表使用外键约束,以保证 id 编号在您想要的范围内。外键约束甚至适用于自动递增列。
pragma foreign_keys=on;
create table row_numbers (n integer primary key);
insert into row_numbers values (1);
insert into row_numbers values (2);
insert into row_numbers values (3);
insert into row_numbers values (4);
insert into row_numbers values (5);
create table test_row_numbers (
row_id integer primary key autoincrement,
other_columns varchar(35) not null,
foreign key (row_id) references row_numbers (n)
);
insert into test_row_numbers (other_columns) values ('s');
insert into test_row_numbers (other_columns) values ('s');
insert into test_row_numbers (other_columns) values ('s');
insert into test_row_numbers (other_columns) values ('s');
insert into test_row_numbers (other_columns) values ('s');
第六次插入失败,出现“错误:外键约束失败”。
我不认为使用自动增量是完全安全的。在其他平台上,回滚会在序列中留下间隙。如果您不使用自动增量,则可以通过从“row_numbers”中选择 id 号来安全地插入行。
insert into test_row_numbers values
(
(select min(n)
from row_numbers
where n not in
(select row_id from test_row_numbers)),
's'
);
CHECK() 约束
下面的主键约束保证 id 编号为整数。CHECK() 约束保证整数在正确的范围内。您的应用程序可能仍然需要处理由回滚引起的间隙。
create table test_row_numbers (
row_id integer primary key autoincrement,
other_columns varchar(35) not null,
check (row_id between 1 and 5)
);