xra*_*alf 9 sqlite constraints unique-constraint
我创建了连接表t1和t2的表t1t2,如下所示:
CREATE TABLE t1t2(
id integer primary key,
t1_id integer,
t2_id integer,
foreign key(t1_id) references t1(id),
foreign key(t2_id) references t2(id));
Run Code Online (Sandbox Code Playgroud)
是否可以定义一个约束(限制),它只启用元组的唯一值(t1_id,t2_id)?或者我应该在应用程序中检查这个?
Lar*_*tig 15
CREATE UNIQUE INDEX idx_twocols ON t1t2(t1_id, t2_id)
Run Code Online (Sandbox Code Playgroud)
您可能需要为两列中的每一列的声明添加NOT NULL.
或者,你可以选择放弃主键列(如果你使用它的全部是唯一)和创建的组合主键t1_id和t2_id:
CREATE TABLE t1t2(
t1_id integer NOT NULL,
t2_id integer NOT NULL,
PRIMARY KEY (t1_id, t2_id),
foreign key(t1_id) references t1(id),
foreign key(t2_id) references t2(id));
Run Code Online (Sandbox Code Playgroud)
PRIMARY KEY是UNIQUE索引的特例.使用复合PRIMARY KEY可以保存一列和一个索引,但需要您的应用程序知道这两个t1_id并t2_id从表中检索单行.
| 归档时间: |
|
| 查看次数: |
7034 次 |
| 最近记录: |