错误代码:1215。不能添加外键约束[复制]

时间:2022-09-22 17:51:38

This question already has an answer here:

这个问题已经有了答案:

I have two tables and I want there reference between the two.

我有两张桌子,我想要两者之间的参考。

I tried using the alter table command, but it gives me an error, can anyone help me please?

我尝试使用alter table命令,但是它给了我一个错误,谁能帮我?

CREATE TABLE `registos` (
`data_registo` char(10) NOT NULL,
`hora_registo` time NOT NULL,
`idSensor` varchar(8) NOT NULL,
`Temperatura` char(6) DEFAULT NULL,
`Humidade` char(6) DEFAULT NULL,
`pt_orvalho` char(6) DEFAULT NULL,
`idRegisto` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`idRegisto`,`idSensor`,`data_registo`,`hora_registo`),
KEY `fk_registos_sensores1_idx` (`idSensor`),
CONSTRAINT `fk_registos_sensores1` FOREIGN KEY (`idSensor`) REFERENCES `sensores`   (`idSensor`) ON DELETE NO ACTION ON UPDATE NO ACTION
 )




CREATE TABLE `alarmes` (
`idAlarme` int(11) NOT NULL AUTO_INCREMENT,
`descricao_alarme` varchar(45) DEFAULT NULL,
`data_criacao` datetime DEFAULT CURRENT_TIMESTAMP,
`idRegisto` int(11) NOT NULL,
PRIMARY KEY (`idAlarme`,`idRegisto`)
) 

ALTER TABLE alarmes

ADD CONSTRAINT FK_alarmes1
FOREIGN KEY (idRegisto) REFERENCES registos(idRegisto)
ON UPDATE CASCADE
ON DELETE CASCADE;

1 个解决方案

#1


2  

You have defined idRegisto as a signed integer in one table and an unsigned integer in the other table. Foreign key references can only be made between fields with the same type.

您已经将idRegisto定义为一个表中的有符号整数和另一个表中的无符号整数。外键引用只能在具有相同类型的字段之间进行。

Another problem is that you created the table with the name registos but you are trying to add a key referencing the table registo.

另一个问题是,您创建了带有名称registos的表,但是您正在尝试添加一个引用表registo的键。

#1


2  

You have defined idRegisto as a signed integer in one table and an unsigned integer in the other table. Foreign key references can only be made between fields with the same type.

您已经将idRegisto定义为一个表中的有符号整数和另一个表中的无符号整数。外键引用只能在具有相同类型的字段之间进行。

Another problem is that you created the table with the name registos but you are trying to add a key referencing the table registo.

另一个问题是,您创建了带有名称registos的表,但是您正在尝试添加一个引用表registo的键。