Skip to content Skip to sidebar Skip to footer

Insert Data Into A Table With A Foreign Key Sql

I need to insert some data into the 'ItemBook' table after inserting the following values for one row for the 'Item' Table: Name='Clippers', itemLink='amazon.com' description='hair

Solution 1:

Is there any specific reason to not use integer IDs? I would do the following:

CREATETABLE Item (
Id INTEGERNOTNULLIDENTITYPRIMARY KEY,
Name VARCHAR(100) NOTNULL,
itemLink VARCHAR(100) NOTNULL,
description VARCHAR(1000) NOTNULL,
);

CREATETABLE ItemBook (
Id INTEGERNOTNULLIDENTITYPRIMARY KEY,
ItemName VARCHAR(100) NOTNULL,
Publisher VARCHAR(100) NOTNULL,
ItemId INTEGERNOTNULL,
FOREIGN KEY (ItemId) REFERENCES Item(Id)
);

INSERTINTO ItemBook Values(1, 'ItemName', 'Publisher', 0)

What are your thoughts?

Edit 1. Based on your response and example, I have produced the following SQL for SQLITE (should work fine in other DBs as well)

CREATETABLE Item (
Name VARCHAR(100) NOTNULL,
ItemLink VARCHAR(100) NOTNULL,
Description VARCHAR(1000) NOTNULL,
PRIMARY KEY (Name)
);

CREATETABLE ItemBook (
ItemName VARCHAR(100) NOTNULL,
Publisher VARCHAR(100) NOTNULL,
PRIMARY KEY (ItemName),
FOREIGN KEY (ItemName) REFERENCES Item(Name)
);

INSERTINTO Item (Name, ItemLink, Description) VALUES("Test Book", "http://www.testlink.com/", "This is a test book");

INSERTINTO ItemBook (ItemName, Publisher) Values("Test Book", "Test Publisher");

SELECT*FROM Item i JOIN ItemBook b on b.ItemName = i.Name

Check the result in this print

Post a Comment for "Insert Data Into A Table With A Foreign Key Sql"