SQLite外键示例

时间:2012-12-18 14:23:17

标签: python sql sqlite insert foreign-keys

我不是sql / sqlite的专家.. 假设我们有两个表:

CREATE TABLE child (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
);

CREATE TABLE MyTableB(
  dog TEXT, 
  FOREIGN KEY(dogList) REFERENCES child(id)
);

INSERT将如何?我的createTable操作是否正确? 我想拥有: 一个孩子可以有一只以上的狗 一只狗可以有更多的孩子

修改

如果我希望所有孩子和每个孩子都有与该孩子相关的狗列表怎么办?

2 个答案:

答案 0 :(得分:52)

许多对多

为了支持零个或多个狗和属于零个或多个孩子的狗的孩子,您的数据库表结构需要支持多对多关系。这需要三个表:

CREATE TABLE child (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT
);


CREATE TABLE dog (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    dog TEXT
);

CREATE TABLE child_dog {
    child_id INTEGER,
    dog_id INTEGER,
    FOREIGN KEY(child_id) REFERENCES child(id),
    FOREIGN KEY(dog_id) REFERENCES dog(id)
};

如何插入

对三个表中的每个表的插入必须是单独的SQL语句,但可以在同一事务的上下文中进行。插入child_dog表(称为映射表)必须在插入子表和狗表后插入。这有两个相关的原因:

  1. 你需要知道孩子和狗的标识符 插入此表。
  2. 由于外键约束,如果引用的子和/或狗在数据库或事务中不存在,则插入child_dog表将失败。
  3. 以下是insert的一些示例SQL语句:

    INSERT INTO child VALUES(NULL, 'bobby');
    SELECT last_insert_rowid(); -- gives the id of bobby, assume 2 for this example
    INSERT INTO dog VALUES(NULL, 'spot');
    SELECT last_insert_rowid(); -- gives the id of spot, assume 4 for this example
    INSERT INTO child_dog VALUES(2, 4);
    

    在Python中插入

    虽然你的问题没有提到python,但是这个问题上有一个python标签,所以我假设你想知道如何在python中做到这一点。 python中的sqlite3模块提供了一个很好的小快捷方式,使您无需显式运行'last_insert_rowid()'函数。

    # Import the sqlite3 module
    import sqlite3
    # Create a connection and cursor to your database
    conn = sqlite3.connect('example.db')
    c = conn.cursor()
    # Insert bobby
    c.execute("""INSERT INTO child VALUES(NULL, 'bobby')""")
    # The python module puts the last row id inserted into a variable on the cursor
    bobby_id = c.lastrowid
    # Insert spot
    c.execute("""INSERT INTO dog VALUES(NULL, 'spot')""")
    spot_id = c.lastrowid
    # Insert the mapping
    c.execute("""INSERT INTO child_dog VALUES(?, ?)""", (bobby_id, spot_id));
    # Commit
    conn.commit()
    conn.close()
    

答案 1 :(得分:0)

你需要有三张桌子。这是Many-to-Many关系的一个示例。

Child
- ChildID (PK)
- Name

Dog
- DogID   (PK)
- DogName

Child_Dog
- ChildID (FK)   
- DogID   (FK)