我想有一种级联主键,如下所示。
根表:
CREATE TABLE IF NOT EXISTS `root` (
`id` MEDIUMINT UNSIGNED ZEROFILL NOT NULL auto_increment
PRIMARY KEY (`id`))
ENGINE = InnoDB;
父表:
CREATE TABLE IF NOT EXISTS `parent` (
`id_root` MEDIUMINT UNSIGNED ZEROFILL NOT NULL,
`id` INT UNSIGNED ZEROFILL NOT NULL,
PRIMARY KEY (`id_root`,`id`),
CONSTRAINT `fk_root`
FOREIGN KEY (`id_root`)
REFERENCES `root` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
子表:
CREATE TABLE IF NOT EXISTS `child` (
`id_root` MEDIUMINT UNSIGNED ZEROFILL NOT NULL,
`id_parent` INT UNSIGNED ZEROFILL NOT NULL,
`id` SMALLINT UNSIGNED ZEROFILL NOT NULL,
PRIMARY KEY (`id_root`,`id_parent`,`id`),
CONSTRAINT `fk_parent`
FOREIGN KEY (`id_root`,`id_parent`)
REFERENCES `parent` (`id_root`,`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
对于INSERT语句,将给出FOREIGN KEY部分,例如:像:
INSERT INTO `child` (`id_root`, `id_parent`) VALUES (00000001, 00000001);
不幸的是我遇到了两个问题:
id
设置为0(即使声明为NOT NULL)id_root
和id_parent
(猜测是由于主键违反id
= 0,因为某些原因,mysql没有像通常那样抛出错误) 我玩过UNIQUE KEY而不是PRIMARY KEY,但结果相同。创建表时,引擎会拒绝id
的Auto_increment。
除了提供id
值,例如通过触发器,还有另一种方法可以使这项工作?