简体   繁体   中英

How can I create a FOREIGN KEY in SQLite?

I have a table already created, here's the code:

CREATE TABLE "Préstamo_Biomédica" (
    ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    Entregado CHAR(100),
    Fech_Pres DATE, 
    Fech_Devu DATE,
    Nota TEXT
)

And I'm trying to create a table with a FOREIGN KEY with this code:

CREATE TABLE Inventario_Biomédica (
    Id_Pieza INT PRIMARY KEY,
    Nom_Pieza CHAR(100),
    Cantidad INT,
    Des_Pieza TEXT,
    Gastable BIT,
    Fech_Ent DATE,
    P_Módulo BIT,
    FOREIGN KEY (ID) REFERENCES Préstamo_Biomédica(ID_Préstamo),
)

I hope you guys can help me...

CREATE TABLE "Préstamo_Biomédica" (
ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Entregado CHAR(100),
Fech_Pres DATE, 
Fech_Devu DATE,
Nota TEXT
)

CREATE TABLE Inventario_Biomédica (
Id_Pieza INT PRIMARY KEY,
Nom_Pieza CHAR(100),
Cantidad INT,
Des_Pieza TEXT,
Gastable BIT,
Fech_Ent DATE,
P_Módulo BIT,
FOREIGN KEY (ID_Préstamo) REFERENCES Préstamo_Biomédica(ID),
)

Give foreign Key Column Name right after FOREIGN KEY and parent tables Primary key column after REFERENCES

You should use only ASCII characters in identifiers. If not, you must quote them.

To get an autoincrementing ID, you must use INTEGER, not INT.

The FOREIGN KEY clause refers to a column that already must exist in the table's column list. And the parent's table/column names come after the REFERENCE:

CREATE TABLE "Inventario_Biomédica" (
    Id_Pieza INTEGER PRIMARY KEY,
    Nom_Pieza CHAR(100),
    Cantidad INT,
    Des_Pieza TEXT,
    Gastable BIT,
    Fech_Ent DATE,
    "P_Módulo" BIT,
    "ID_Préstamo" INT,
    FOREIGN KEY ("ID_Préstamo") REFERENCES "Préstamo_Biomédica"(ID),
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM