【问题标题】:Foreign key constrait fail外键约束失败
【发布时间】: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


【解决方案1】:

SQL Fiddle

MySQL 5.5.30 架构设置:

create table comuni(
comune varchar(20) primary key,
cap char(5) not null,
abitanti int not null
);


create table mercati(
ubicazione varchar(20) not null,
comune varchar(20) not null,
primary key(ubicazione,comune),
foreign key(comune) references comuni(comune)
);

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

【讨论】:

  • 现在它可以工作了,但是通过这种方式我可以这样做:插入 posteggi(identificativo,mq,ubicazione,comune) values('10',10,'aaaaa','tribano');不尊重参考完整性,因为表 mercati 中不存在 comune=tribano 和 ubicazione=aaaaa 的行
  • @a_horse_with_no_name :哦。不知道。看到小提琴并纠正了问题。我们也可以创建我不知道的复合外键。谢谢指正。
  • commercianti(codice_fiscale) 可能为空,但现在我尝试不使用它
  • @a_horse_with_no_name :删除它。
猜你喜欢
  • 1970-01-01
  • 2013-03-04
  • 2016-08-17
  • 2011-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-23
  • 2021-12-04
相关资源
最近更新 更多