多列上的Sqlite主键

时间:2009-04-09 15:17:32

标签: sqlite primary-key ddl composite-primary-key

在SQLITE中为多于1列指定主键的语法是什么?

9 个答案:

答案 0 :(得分:736)

根据documentation,它是

CREATE TABLE something (
  column1, 
  column2, 
  column3, 
  PRIMARY KEY (column1, column2)
);

答案 1 :(得分:152)

CREATE TABLE something (
  column1 INTEGER NOT NULL,
  column2 INTEGER NOT NULL,
  value,
  PRIMARY KEY ( column1, column2)
);

答案 2 :(得分:40)

是。但请记住,这样的主键允许两列中的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

答案 3 :(得分:26)

基本:

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
);

答案 4 :(得分:14)

主键字段应声明为非空(这是非标准定义 主键是它必须是唯一的而不是null。但下面是一个很好的做法 任何DBMS中的所有多列主键。

create table foo
(
  fooint integer not null
  ,foobar string not null
  ,fooval real
  ,primary key (fooint, foobar)
)
;

答案 5 :(得分:8)

从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

答案 6 :(得分:2)

In another way, you can also make the two column primary key unique and the auto-increment key primary. Just like this: https://stackoverflow.com/a/6157337

答案 7 :(得分:1)

以下代码在SQLite中使用 2列作为主键创建了一个表。

解决方案:

CREATE TABLE IF NOT EXISTS users (id TEXT NOT NULL, name TEXT NOT NULL, pet_name TEXT, PRIMARY KEY (id, name))

答案 8 :(得分:0)

PRIMARY KEY (id, name)对我不起作用。添加约束对我来说确实有用。

CREATE TABLE IF NOT EXISTS customer (id INTEGER, name TEXT, user INTEGER, CONSTRAINT PK_CUSTOMER PRIMARY KEY (user, id))