无法添加或更新子行:实际服务器上的外键约束失败

时间:2013-11-24 12:49:17

标签: php mysql sql mysql-workbench

我的网络服务器上的数据库存在问题,但它正在本地主机上运行。

这是我的数据库设计: enter image description here

这是这三个表的代码:

CREATE TABLE IF NOT EXISTS `zeko2006_salesSystem`.`users` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`admin` TINYINT(1) NULL DEFAULT 0,
`name` VARCHAR(50) NULL,
`mail` VARCHAR(100) NULL,
`phone` DECIMAL(20) NULL,
`username` VARCHAR(45) NULL,
`password` VARCHAR(50) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `username_UNIQUE` (`username` ASC),
UNIQUE INDEX `mail_UNIQUE` (`mail` ASC),
UNIQUE INDEX `user_id_UNIQUE` (`id` ASC))
ENGINE = InnoDB

COMMENT = '<double-click to overwrite multiple objects>';

这是公司代码:

CREATE TABLE IF NOT EXISTS `zeko2006_salesSystem`.`company` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`cp_source` VARCHAR(100) NULL,
`call_date` VARCHAR(100) NULL,
`cp_mail` VARCHAR(100) NULL,
`cp_mail_2` VARCHAR(100) NULL,
`cp_phone` DECIMAL(20) NULL,
`cp_phone_2` DECIMAL(20) NULL,
`cp_address` VARCHAR(100) NULL,
`cp_website` VARCHAR(100) NULL,
`cp_category` VARCHAR(100) NULL,
`user_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`id`, `user_id`),
UNIQUE INDEX `cp_id_UNIQUE` (`id` ASC),
UNIQUE INDEX `cp_name_UNIQUE` (`cp_name` ASC),
UNIQUE INDEX `cp_phone_UNIQUE` (`cp_phone` ASC),
UNIQUE INDEX `cp_website_UNIQUE` (`cp_website` ASC),
INDEX `fk_user_id_idx` (`user_id` ASC),
CONSTRAINT `fk_user_id`
FOREIGN KEY (`user_id`)
REFERENCES `zeko2006_salesSystem`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
COMMENT = '<double-click to overwrite multiple objects>';

这是公司代表代码:

CREATE TABLE IF NOT EXISTS `zeko2006_salesSystem`.`company_rep` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`cp_rep_name` VARCHAR(100) NULL,
`cp_rep_position` VARCHAR(100) NULL,
`cp_rep_phone` VARCHAR(100) NULL,
`cp_rep_mail` VARCHAR(100) NULL,
`company_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`id`, `company_id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC),
UNIQUE INDEX `company_id_UNIQUE` (`company_id` ASC),
CONSTRAINT `fk_cpmpany_id`
FOREIGN KEY (`company_id`)
REFERENCES `zeko2006_salesSystem`.`company` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
COMMENT = '<double-click to overwrite multiple objects>';

当我插入新用户然后插入公司时:

INSERT INTO zeko2006_salesSystem.company (
    id, cp_source, call_date, cp_name, cp_mail, cp_mail_2,
    cp_phone, cp_phone_2, cp_address, cp_website, cp_category, user_id
) VALUES ('2', 'Friends', '25-4-2001', 'Media Club Egypt',
    'mc@gmail.com', 'mc@gmail.com', '01117962758',
    '01117962758', 'Egypt', 'www.sjdbfj.com', 'Media', '1'
);

这很好但是当我向这家公司插入公司代表时,它给了我这个错误:

Cannot add or update a child row: a foreign key constraint fails    (`zeko2006_salesSystem`.`company_rep`, CONSTRAINT `fk_cpmpany_id` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) 

提前致谢。

1 个答案:

答案 0 :(得分:0)

company表中,您有:

UNIQUE INDEX `cp_name_UNIQUE` (`cp_name` ASC),

此索引引用了不存在的列。

否则,添加该列后,一切都适合我。

SQL fiddle