首页 文章

SQLite组合键(2个外键)链接表

提问于
浏览
15

我已经阅读了SQLite create table语句的相当酷的BNF语法

在这里找到:http://www.sqlite.org/lang_createtable.html

我想知道如何在这些之间创建链接表

我有一张 table ,比方说,房子和另一个electric_items .

我想创建一个链接表,将house_id和item_id作为复合键,但我不知道我该怎么做,它似乎不允许主键成为外键?

N.B我想要第三个字段pap_tested,它存储房子中电子项目的日期是pap_tested,所以这个链接表通过复合主键似乎是最好的方法 .

4 回答

  • 0

    这些中的任何一个都适用于您的关联表:

    create table house_items (
        house_id integer not null,
        item_id  integer not null,
        foreign key (house_id) references houses(id),
        foreign key (item_id) references electrical_items(id),
        primary key (house_id, item_id)
    )
    
    create table house_items (
        house_id integer not null references houses(id),
        item_id  integer not null references electrical_items(id),
        primary key (house_id, item_id)
    )
    

    你可能也想要separate (single column) indexes on house_items.house_id and house_items.item_id .

  • 1

    只是为了补充第一个答案,为约束添加名称是一个好习惯,如下面的代码:

    create table house_items (
        house_id integer not null,
        item_id  integer not null,
        constraint house_items_pk primary key (house_id, item_id),
        constraint house_items_house_fk foreign key (house_id) references houses(id),
        constraint house_items_items_fk foreign key (item_id) references electrical_items(id));
    
  • 2

    对于那些需要这种关系的设计而言,没有禁止PRIMARY KEY也不是禁止外键 . 但是,您的问题不是其中之一,因为链接表中的自然PRIMARY KEY是两列的组合,每个列都有一个FOREIGN KEY返回到其他表之一 .

  • 30

    我创建了一个表,其中包含两个外键以及更新级联和删除级联的选项 .

    CREATE TABLE category_subcategory
    (
     category_subcategory_id INTEGER PRIMARY KEY,
     category_id             INTEGER NOT NULL,
     subcategory_id          INTEGER NOT NULL,
     FOREIGN KEY(category_id) REFERENCES categories(id) ON DELETE CASCADE ON
     UPDATE CASCADE,
     FOREIGN KEY(subcategory_id) REFERENCES subcategories(subcategory_id) ON
     DELETE CASCADE ON UPDATE CASCADE
     );
    

相关问题