使用外键SQL将数据插入到表中
在为‘Item’表的一行插入下列值之后,我需要向‘ItemBook’表中插入一些数据:
Name='Clippers', itemLink='amazon.com' description='hair clippers'
现在我还想将一些数据插入到ItemBook表中,但我不确定如何对具有外键的表执行此操作。以下是SQL代码:
CREATE TABLE Item (
Name VARCHAR(100) NOT NULL,
itemLink VARCHAR(100) NOT NULL,
description VARCHAR(1000) NOT NULL,
PRIMARY KEY (Name)
);
CREATE TABLE ItemBook (
ItemName VARCHAR(100) NOT NULL,
Publisher VARCHAR(100) NOT NULL,
PRIMARY KEY (ItemName),
FOREIGN KEY (ItemName) REFERENCES Item(Name)
);
我的尝试:
INSERT INTO itemBook (Name, Publisher)
VALUES ('Clippers', 'Bob');
错误消息:
Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column. To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
其他尝试:
INSERT INTO eventbook (EventName, Publisher)
SELECT E.name
FROM event E
WHERE E.name = eventbook.EventName;
错误消息:
Error Code: 1054. Unknown column 'eventbook.EventName' in 'where clause'
解决方案
不使用整数ID有什么特殊原因吗?我将执行以下操作:
CREATE TABLE Item (
Id INTEGER NOT NULL IDENTITY PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
itemLink VARCHAR(100) NOT NULL,
description VARCHAR(1000) NOT NULL,
);
CREATE TABLE ItemBook (
Id INTEGER NOT NULL IDENTITY PRIMARY KEY,
ItemName VARCHAR(100) NOT NULL,
Publisher VARCHAR(100) NOT NULL,
ItemId INTEGER NOT NULL,
FOREIGN KEY (ItemId) REFERENCES Item(Id)
);
INSERT INTO ItemBook Values(1, 'ItemName', 'Publisher', 0)
您的想法是什么?
编辑1.根据您的回应和示例,我为SQLITE生成了以下SQL(在其他数据库中应该也可以正常工作)
CREATE TABLE Item (
Name VARCHAR(100) NOT NULL,
ItemLink VARCHAR(100) NOT NULL,
Description VARCHAR(1000) NOT NULL,
PRIMARY KEY (Name)
);
CREATE TABLE ItemBook (
ItemName VARCHAR(100) NOT NULL,
Publisher VARCHAR(100) NOT NULL,
PRIMARY KEY (ItemName),
FOREIGN KEY (ItemName) REFERENCES Item(Name)
);
INSERT INTO Item (Name, ItemLink, Description) VALUES("Test Book", "http://www.testlink.com/", "This is a test book");
INSERT INTO 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
相关文章