20

I am not an expert in sql / sqlite.. suppose we have two tables:

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

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

how will the INSERT? is correct my createTable operations? I would like to have: a child can have more than one dog a dog can have more children

EDIT

What if I wanted all the children and for each child a list of dogs associated with that child?

1
  • FYI: AUTOINCREMENT is usually not needed and adds extra overhead. In most cases, INTEGER PRIMARY KEY alone is sufficient for an auto-incrementing id column. sqlite.org/autoinc.html Jul 9, 2020 at 5:32

3 Answers 3

61

Many-To-Many

In order to support a child having zero or more dogs and a dog belonging to zero or more children, your database table structure needs to support a Many-To-Many relationship. This requires three tables:

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

How to Insert

An insert into each of the three tables must be separate SQL statements, but can take place in the context of same transaction. Inserts into the child_dog table (known as the mapping table) must happen after inserts into the child and dog tables. This is for two related reasons:

  1. You need to know the identifiers of both the child and the dog in order to to insert into this table.
  2. Because of the foreign key constraint, an insert into the child_dog table would fail if the child and/or dog referenced do not exist in the database or transaction.

Here are some example SQL statements for insert:

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

Inserting In Python

Although your question did not mention python, there is a python tag on this question so I'll assume you want to know how to do this in python. The sqlite3 module in python provides a nice little shortcut which saves you from having to run the 'last_insert_rowid()' function explicitly.

# 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()
6
  • sorry, and if I want to do a SELECT (all), I use a join? how will the query?
    – Safari
    Dec 19, 2012 at 9:53
  • 3
    @GgSalent depends on what you are attempting to retrieve with your select, here are some examples: SELECT name, dog FROM child, dog, child_dog WHERE child.id = child_dog.child_id AND dog.id = child_dog.dog_id for selecting all combinations and SELECT dog FROM child, dog, child_dog WHERE child.id = child_dog.child_id AND dog.id = child_dog.dog_id AND name = 'bobby' for the dogs owned by bobby. Inner joins, aggregates with group by clauses, and such are also options depending on what information you want.
    – ken.ganong
    Dec 19, 2012 at 16:01
  • Scratching my head trying to wrap around how to do relational inserts and this is one of the cleanest, easiest to understand examples I've run across. Bonus points because I'm using Python.
    – Ryan
    Jun 12, 2014 at 4:00
  • 4
    I might recommend removing AUTOINCREMENT from your answer, because it is not required, and not recommended by sqlite, just to avoid any confusion. See sqlite.org/autoinc.html (1.1).
    – Peter M
    Sep 18, 2016 at 1:11
  • 1
    If you're using Python, check out SQLAlchemy. It provides a powerful object relational mapper (ORM) that's made for doing things like many-to-many relationships. docs.sqlalchemy.org/en/13/orm/… Jul 9, 2020 at 5:38
0

you need to have three tables for this. This is an example of Many-to-Many Relationship.

Child
- ChildID (PK)
- Name

Dog
- DogID   (PK)
- DogName

Child_Dog
- ChildID (FK)   
- DogID   (FK)
2
  • 1
    you need to insert first on child and dog tables. since Child_Dog is dependent on the values of the two tables.
    – John Woo
    Dec 18, 2012 at 14:56
  • 1
    if the dog or child table PK is AUTOINCREMENT type..how can I know this value to insert it into Child_Dog table? An example of ISERT operation is welcome..
    – Safari
    Dec 18, 2012 at 15:08
-1
CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
2
  • 2
    It's your responsibility to include an explanation of what this does, and in this case, how it's better / different than the highly voted existing answer. Do not post code only answers. Mar 18, 2022 at 17:39
  • 3
    Please read "How to Answer" and "Explaining entirely code-based answers". It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code. Mar 20, 2022 at 23:03

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.