Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql SQL脚本插入到值中无法插入?_Mysql_Foreign Keys_Primary Key - Fatal编程技术网

Mysql SQL脚本插入到值中无法插入?

Mysql SQL脚本插入到值中无法插入?,mysql,foreign-keys,primary-key,Mysql,Foreign Keys,Primary Key,我使用脚本在同一个数据库中创建了一个表。两个表都制作好后,我制作了一个单独的脚本在表中插入一组值,但是其中一个脚本似乎没有向表中插入任何数据,但出现了错误。 这些是我的桌子 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,

我使用脚本在同一个数据库中创建了一个表。两个表都制作好后,我制作了一个单独的脚本在表中插入一组值,但是其中一个脚本似乎没有向表中插入任何数据,但出现了错误。 这些是我的桌子

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)
);
在另一个脚本中

CREATE TABLE IF NOT EXISTS postcodes(
postcode VARCHAR(20) NOT NULL,
address_line_2 VARCHAR(20),
city VARCHAR(40) NOT NULL,
PRIMARY KEY(postcode)    
);
将数据插入表的脚本如下所示。 这一个工作没有任何错误,并且成功地填充了表

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');
这是一个出现错误信息的

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');
出现的错误消息是

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

您有一个外键约束,指定
customers(postcode)
引用
postcodes
表中的有效邮政编码

然后,您尝试插入
'DH1 7SO'
,但它不起作用,因为此邮政编码不在
邮政编码中

外键引用就是这样工作的。数据库正按照它应该的方式工作,并且完全按照您指示的方式工作


如果要插入有效行而忽略无效行,请使用
INSERT
上的
IGNORE
选项(请参阅)。

父表中没有邮政编码
'DH1 7SO'
,即在表
邮政编码中,因此失败。