在SQLITE中在多于1列上指定主键的语法是什么?
根据文档,它是
CREATE TABLE something ( column1, column2, column3, PRIMARY KEY (column1, column2) );
CREATE TABLE something ( column1 INTEGER NOT NULL, column2 INTEGER NOT NULL, value, PRIMARY KEY ( column1, column2) );
是.但请记住,这样的主键允许NULL
两列中的值多次.
像这样创建一个表:
sqlite> CREATE TABLE something ( column1, column2, value, PRIMARY KEY (column1, column2));
现在这没有任何警告:
sqlite> insert into something (value) VALUES ('bla-bla'); sqlite> insert into something (value) VALUES ('bla-bla'); sqlite> select * from something; NULL|NULL|bla-bla NULL|NULL|bla-bla
基础:
CREATE TABLE table1 ( columnA INTEGER NOT NULL, columnB INTEGER NOT NULL, PRIMARY KEY (columnA, columnB) );
如果您的列是其他表的外键(常见情况):
CREATE TABLE table1 ( table2_id INTEGER NOT NULL, table3_id INTEGER NOT NULL, FOREIGN KEY (table2_id) REFERENCES table2(id), FOREIGN KEY (table3_id) REFERENCES table3(id), PRIMARY KEY (table2_id, table3_id) ); CREATE TABLE table2 ( id INTEGER NOT NULL, PRIMARY KEY id ); CREATE TABLE table3 ( id INTEGER NOT NULL, PRIMARY KEY id );
主键字段应声明为非null(这是非标准的,因为主键的定义是它必须是唯一的而不是null).但对于任何DBMS中的所有多列主键,以下是一个很好的做法.
create table foo ( fooint integer not null ,foobar string not null ,fooval real ,primary key (fooint, foobar) ) ;
从SQLite的3.8.2版开始,显式NOT NULL规范的替代方法是"WITHOUT ROWID"规范:[ 1 ]
NOT NULL is enforced on every column of the PRIMARY KEY in a WITHOUT ROWID table.
"没有ROWID"表具有潜在的效率优势,因此更简洁的替代方案是:
CREATE TABLE t ( c1, c2, c3, PRIMARY KEY (c1, c2) ) WITHOUT ROWID;
例如,在sqlite3提示符下:
sqlite> insert into t values(1,null,3);
Error: NOT NULL constraint failed: t.c2