【问题标题】:Unique Constraint on Foreign Key Columns外键列的唯一约束
【发布时间】:2015-04-06 11:57:59
【问题描述】:

我正在尝试将unique constraint 添加到两个外键:

CREATE TABLE tagsInBlog(
    id_tag int(10) not null auto_increment,
    id_word int(10) not null,
    id_page int(11),
    PRIMARY KEY(id_tag),
    FOREIGN KEY (id_page) REFERENCES archive(id),
    FOREIGN KEY (id_word) REFERENCES tagwords(id_word)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

ALTER TABLE tagsinblog
  ADD UNIQUE tagBlogConstraint (id_word, id_page);

创建时我没有收到任何错误,但是当我尝试插入时我得到:

MYSQL ERROR 367421 (could not save new tag data into Mysql): Error 1452 (23000):无法添加或更新子行:外键 约束失败(sqse_001.tagsinblog, CONSTRAINT tagsinblog_ibfk_2 外键 (id_word) 引用 tagwords (id_word))

当我尝试在没有唯一约束的情况下插入同一个表时,我没有任何问题。

【问题讨论】:

    标签: mysql sql reference constraints unique


    【解决方案1】:

    我研究了您的问题陈述,并假设以下几点

    您的archive 表可能如下所示

    CREATE TABLE IF NOT EXISTS `archive` ( `id` int(11) NOT NULL AUTO_INCREMENT,
    `descrp` varchar(10) NOT NULL DEFAULT '', PRIMARY KEY (id) ) ENGINE=InnoDB
    

    tagwords 表可能看起来像这样

     CREATE TABLE IF NOT EXISTS `tagwords` ( `id_word` int(11) NOT NULL
     AUTO_INCREMENT, `descrp` varchar(10) NOT NULL DEFAULT '', 
     PRIMARY KEY (id_word) ) ENGINE=InnoDB
    

    现在查询表tagsInBlog

    CREATE TABLE tagsInBlog(
    id_tag int(10) not null auto_increment,
    id_word int(10) not null,
    id_page int(11),
    PRIMARY KEY(id_tag),
    FOREIGN KEY (id_page) REFERENCES archive(id),
    FOREIGN KEY (id_word) REFERENCES tagwords(id_word)
    )ENGINE=INNODB DEFAULT CHARSET=utf8; 
    

    更改表tagsInBlog的查询

    ALTER TABLE tagsinblog ADD UNIQUE tagBlogConstraint (id_word, id_page);
    

    以下插入语句工作正常

    INSERT INTO `test`.`tagsinblog` (`id_tag`, `id_word`, `id_page`) 
    VALUES (NULL, '1', '1'), (NULL, '1', '2');
    

    假设您在表 tagswordsarchive 中有相应的条目

    但是,如果您尝试将任何值插入为foreign key,而该值在表archivetagwords 中不存在,则会引发以下错误

     #1452 - Cannot add or update a child row: a foreign key constraint fails  
     (`test`.`tagsinblog`, CONSTRAINT `tagsinblog_ibfk_2` 
     FOREIGN KEY (`id_word`) REFERENCES `tagwords` (`id_word`)) 
    

    所以请确保您在所有表格中都有正确的条目。

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 2011-05-28
      • 2016-01-15
      • 1970-01-01
      • 2015-06-15
      相关资源
      最近更新 更多