[英]SQL script INSERT INTO values unnable to be inserted?
I used a script to make a tables within the same database. 我使用脚本在同一数据库中制作了一个表。 Once both tables were made, I made a seperate script to insert a set of values in the table, however with one of the scripts it doesnt seem to insert any data into the table, but comes up with the error.
制作完两个表后,我制作了一个单独的脚本以在表中插入一组值,但是对于其中一个脚本,它似乎没有在表中插入任何数据,但出现了错误。 These are my tables;
这些是我的桌子;
CREATE TABLE IF NOT EXISTS customers(
customer_id INT UNSIGNED NOT NULL,
first_name VARCHAR(20) NOT NULL,
middle_name VARCHAR(20),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
password VARCHAR(40) NOT NULL,
dob DATETIME NOT NULL,
address_line VARCHAR(40) NOT NULL,
postcode VARCHAR(20) NOT NULL,
PRIMARY KEY(customer_id),
FOREIGN KEY(postcode) REFERENCE postcodes(postcode)
);
In a seperate script, 在单独的脚本中,
CREATE TABLE IF NOT EXISTS postcodes(
postcode VARCHAR(20) NOT NULL,
address_line_2 VARCHAR(20),
city VARCHAR(40) NOT NULL,
PRIMARY KEY(postcode)
);
The scripts to insert data into the tables are here. 将数据插入表的脚本在这里。 This one works without any errors and successfully populates the table.
该程序可以正常运行,并且没有任何错误,并且可以成功地填充表格。
INSERT INTO postcodes(postcode,address_line_2,city)
Values
('DH1 568','Forest Lane','Durham'),
('DH1 679','Dry Wood','Durham'),
('DH1 4AS','North Of the Wall','Westeros'),
('DH1 4LA',"Snoop's Crib",'Durham');
And this is the one which comes up with an error message, 这是一则错误消息,
INSERT INTO customers(customer_id,first_name,postcode)
values
('1','Zaak','DH1 568'),
('2','Matt','DH1 679'),
('3','Jon','DH1 4AS'),
('4','Zak','DH1 4LA'),
('5','Gaz','DH1 7SO');
The error message which appears is, 出现的错误信息是,
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`hardware_store`.`customers`, CONSTRAINT `customers_ibfk_1` FOREIGN KEY (`postcode`) REFER
ENCES `postcodes` (`postcode`))
You have a foreign key constraint specifying that customers(postcode)
refers to a valid postal code in the postcodes
table. 您有一个外键约束,指定
customers(postcode)
引用postcodes
表中的有效邮政编码。
Then, you try to insert 'DH1 7SO'
and it doesn't work because this postcode is not in postcodes
. 然后,您尝试插入
'DH1 7SO'
,但由于该邮政编码不在postcodes
,因此它不起作用。
This is how foreign key references work. 这就是外键引用的工作方式。 The database is working exactly as it should and doing exactly what you instructed it to do.
数据库正在按应有的方式工作,并按照您的指示进行操作。
If you want the valid rows to be inserted and the invalid ones ignored, then use the IGNORE
option on INSERT
(see here ). 如果要插入有效行,而忽略无效行,请在
INSERT
上使用IGNORE
选项(请参见此处 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.