【发布时间】:2013-05-29 14:51:12
【问题描述】:
我有 3 张桌子:
create table comuni(
comune varchar(20) primary key,
cap char(5) not null,
abitanti int not null
)ENGINE=InnoDB;
create table mercati(
ubicazione varchar(20) not null,
comune varchar(20) not null,
primary key(ubicazione,comune),
foreign key(comune) references comuni(comune)
)ENGINE=InnoDB;
create table posteggi(
identificativo char(3) not null,
mq int not null,
CHECK(mq>=3),
acquistato bool not null DEFAULT 1,
ubicazione varchar(20) not null,
comune varchar(20) not null,
codice_fiscale char(16),
primary key(identificativo,ubicazione,comune),
foreign key(ubicazione,comune) references mercati(ubicazione,comune),
foreign key(codice_fiscale) references commercianti(codice_fiscale)
)ENGINE=InnoDB;
在第一个表中我插入了两行
+-----------+--------+----------+ |公社 |帽 |阿比特提 | +-----------+--------+----------+ |特里巴诺 | 35020 | 6000 | |蒙塞利斯 | 35023 | 5020 | +-----------+--------+----------+然后在第二行,
+----------------+--------+------------+---------- +----------+ |育碧 |乔鲁诺 | ora_inizio | ora_fine |公社 | +----------------+--------+------------+---------- +----------+ |马志尼广场 |胃肠道 | 07:00:00 | 13:00:00 |特里巴诺 | +----------------+--------+------------+---------- +----------+但是当我尝试执行时
insert into posteggi(identificativo,mq,ubicazione,comune)
values('10',10,'piazza mazzini','tribano');
存在于表mercati中我有这个错误:
错误 1452 (23000):无法添加或更新子行:外键约束失败(ntresold-ES.posteggi,CONSTRAINT posteggi_ibfk_1 FOREIGN KEY (ubicazione, comune) REFERENCES mercati (ubicazione, comune))
是的,问题是“tribano”之前的空格,我将其删除并使用 Pheonix 答案中的代码
【问题讨论】:
-
对于
mercati中的现有行,您似乎在comune的值中有前导空格,而您插入到posteggi中的值'tribano'没有前导空格。 (但这可能是由 SO 上的格式引起的)。 -
另一件事:
posteggi.mq上的检查约束是无用的。 MySQL 不支持检查约束(但它不会告诉你)。 -
如果我确保没有空格,对我有用:sqlfiddle.com/#!2/67d60/1
标签: mysql foreign-keys