无法在子行上添加或更新

时间:2018-05-31 02:04:54

标签: mysql sql

我的项目只有两个表,问题是我不能添加超过已经存在的条目:

drop table categoria;
drop table acceso;

CREATE TABLE categoria (
    cat_id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nombre VARCHAR(50) NOT NULL
);


CREATE TABLE acceso (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ip VARCHAR(30) NOT NULL,
date datetime NOT NULL,
bloqueado tinyint(1) NOT NULL,
categoria int(11) NOT NULL,
comentario TEXT,
FOREIGN KEY (id) REFERENCES categoria(cat_id)
);

这是我改变的脚本:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`c9`.`acceso`, CONSTRAINT `acceso_ibfk_1` FOREIGN KEY (`id`) REFERENCES `categoria` (`cat_id`))

当我尝试添加到“acceso”表时,它会抛出“无法在子行上添加或更新...”:

CREATE TABLE categoria (
    cat_id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nombre VARCHAR(50) NOT NULL
);


CREATE TABLE acceso (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ip VARCHAR(30) NOT NULL,
date datetime NOT NULL,
bloqueado tinyint(1) NOT NULL,
categoria int(11) UNSIGNED NOT NULL,
comentario TEXT,
FOREIGN KEY (categoria) REFERENCES categoria(cat_id)
);

正如你在最后一篇文章中看到的那样,我并没有尝试添加与categoria表不同的东西,两个ID之间是否存在任何差异,但必须有其他我不知道的东西。

编辑:现在我明白了。 FOREIGN KEY指向错误的列(acceso.id而不是acceso.categoria)。

+----+-------+-------+
| id | col_1 | col_2 |
+----+-------+-------+
|  1 | 1.2   |     0 |
|  1 | 7.2   |     0 |
|  1 | 12.1  |     1 |
|  1 | 15.2  |     0 |
|  1 | 16.3  |     1 |
|  1 | 21.1  |     0 |
|  1 | 22.2  |     0 |
|  2 | 3     |     0 |
|  2 | 5     |     1 |
+----+-------+-------+

1 个答案:

答案 0 :(得分:0)

我已经使cat_id INT UNSIGNED,因为它就是在父表上的方式

m/d/yyyy