代码之家  ›  专栏  ›  技术社区  ›  Bogdan Gavril MSFT

多列上的sqlite主键

  •  555
  • Bogdan Gavril MSFT  · 技术社区  · 15 年前

    在sqlite中指定一个以上列的主键的语法是什么?

    9 回复  |  直到 15 年前
        1
  •  716
  •   Brian Campbell Dennis Williamson    10 年前

    根据 documentation 它是

    CREATE TABLE something (
      column1, 
      column2, 
      column3, 
      PRIMARY KEY (column1, column2)
    );
    
        2
  •  148
  •   Czechnology    11 年前
    CREATE TABLE something (
      column1 INTEGER NOT NULL,
      column2 INTEGER NOT NULL,
      value,
      PRIMARY KEY ( column1, column2)
    );
    
        3
  •  40
  •   Deepzz    12 年前

    对。但请记住,这样的主键允许 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
    
        4
  •  26
  •   compte14031879    7 年前

    基本的:

    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
    );
    
        5
  •  14
  •   Waynn Lue    12 年前

    主键字段应声明为非空(这是非标准的定义 主键的作用是它必须是唯一的,不能为空)。但下面是一个很好的实践 任何DBMS中的所有多列主键。

    create table foo
    (
      fooint integer not null
      ,foobar string not null
      ,fooval real
      ,primary key (fooint, foobar)
    )
    ;
    
        6
  •  8
  •   peak    9 年前

    自从3.8.2版的sqlite以来,显式非空规范的另一种选择是“without rowid”规范:[ 1 ]

    NOT NULL is enforced on every column of the PRIMARY KEY
    in a WITHOUT ROWID table.
    

    “without 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

        7
  •  2
  •   Community Lee    7 年前

    从另一方面来说,你也可以 两列主键 unique 以及 自动增量 钥匙 primary . 就像这样: https://stackoverflow.com/a/6157337

        8
  •  0
  •   Naveen Kumar V    6 年前

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

    解决方案:

    CREATE TABLE IF NOT EXISTS users (id TEXT NOT NULL, name TEXT NOT NULL, pet_name TEXT, PRIMARY KEY (id, name))
    
        9
  •  0
  •   Choxmi    6 年前

    PRIMARY KEY (id, name) 不适合我。添加一个约束对我来说做了这项工作。

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