【问题标题】:SQLite composite key (2 foreign keys) Link tableSQLite 复合键(2 个外键)链接表
【发布时间】:2011-12-21 14:41:03
【问题描述】:

我已经阅读了 SQLite 创建表语句的风格很酷的 BNF 语法

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

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

我有一张桌子,比方说房子,还有另一张电气物品。

我想创建一个链接表以将 house_id 和 item_id 作为复合键,但我不确定我将如何去做,它似乎不允许主键成为外键?

注意,我想要第三个字段 pap_tested 存储房屋中的电气项目进行 pap_tested 的日期,因此通过复合主键的链接表似乎是最好的方法。

【问题讨论】:

    标签: sqlite database-design create-table


    【解决方案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】:

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          这些都应该适用于您的关联表:

          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

          【讨论】:

          • 点击链接后,我认为它不适用,因为 house_id 是 house 的主键和 item_id 的主键。
          • 您好,在 Android Studio SQLite3 中,主键是 (_id) "Columns.ID" 我仍然使用 (id) 还是将其更改为 (_id)?
          • @Ken 在这种情况下你会使用_id,语法是foreign key (from_column_list) references to_table(to_column_list)
          猜你喜欢
          • 2016-10-06
          • 2018-10-19
          • 1970-01-01
          • 2018-10-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-06
          相关资源
          最近更新 更多