SQLite composite key (2 foreign keys) Link table

前端 未结 4 1123
再見小時候
再見小時候 2020-12-28 18:45

I\'ve read the rather cool styled BNF grammar for the SQLite create table statement

found here: http://www.sqlite.org/lang_createtable.html

I was wo

相关标签:
4条回答
  • 2020-12-28 19:04

    Either of these should work for your association table:

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

    You'll probably want separate (single column) indexes on house_items.house_id and house_items.item_id as well.

    0 讨论(0)
  • 2020-12-28 19:13

    There is no prohibition about a PRIMARY KEY not also being a FOREIGN KEY for those designs that require this kind of relation. Your problem isn't one of those, however, since the natural PRIMARY KEY in the linking table is a composite of the two columns, each a FOREIGN KEY back to one of the other tables.

    0 讨论(0)
  • 2020-12-28 19:14

    Just to complement the first answer, it's a good practice to add a name to constraints, like the code below:

    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));
    
    0 讨论(0)
  • 2020-12-28 19:20

    I create a table with two foreign keys and options of on update cascade and on delete cascade.

    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
     );
    
    0 讨论(0)
提交回复
热议问题