简体   繁体   English

更改表和外键时出错

[英]error with alter table and foreign key

I have 2 tables : 我有2张桌子:

  • Installers (Fields: id,company,country,experience,name) 安装程序(字段:id,company,country,experience,name)
  • Contacts (Fields: name,phone,address) 联系人(字段:姓名,电话,地址)

I would like to match both names, thereby I could click in one value of the name of Installers and it could show me the values of Contacts table. 我想同时匹配两个名称,因此可以单击Installers名称的一个值,它可以向我显示Contacts表的值。

However when I am trying to set up the foreign key (my child table will probably be Installers , as I have more tables like that and Contacts would be the parent.) It states this error: 但是,当我尝试设置外键时(我的子表可能是Installers,因为我有更多这样的表,而Contacts将是父表。)它指出此错误:

query SQL: 查询SQL:

ALTER TABLE `Installers` 
    ADD  FOREIGN KEY (`name`) 
         REFERENCES `SOLAR_PV`.`Contacts`(`name`) 
         ON DELETE CASCADE ON UPDATE CASCADE;

MySQL ha dicho: Documentación MySQL的地方:Documentación

1452 - Cannot add or update a child row: a foreign key constraint fails ( SOLAR_PV . #sql-32a_183 , CONSTRAINT #sql-32a_183_ibfk_1 FOREIGN KEY ( name ) REFERENCES Contacts ( name ) ON DELETE CASCADE ON UPDATE CASCADE) SOLAR_PV无法添加或更新子行:外键约束失败( SOLAR_PV#sql-32a_183 ,CONSTRAINT #sql-32a_183_ibfk_1 FOREIGN KEY( name )参考Contactsname#sql-32a_183_ibfk_1

Both tables are InnoDB and Contacts.name is indexed as well as Installers.name 这两个表都是InnoDB,Contacts.name和Installers.name都被索引

Primary Key of Installers is id and Primary Key of Contacs is name. Installers的主键是id,Contacs的主键是name。

Any idea about what would be the problem? 有什么问题的想法吗?

It seems your child table contains few records those don't have in master, you can check it by below query- 看来您的子表包含了一些主表中没有的记录,您可以通过以下查询来检查它:

SELECT id FROM Installers ins 
LEFT JOIN SOLAR_PV.Contacts cnt ON ins.name=cnt.name 
WHERE cnt.name IS NULL;

Note: Assuming name is int type for better performance as it is primary key in one table. 注意:假设名称是int类型,以获得更好的性能,因为它是一个表中的主键。

If you get few records by above query then you can follow below 2 approach- 如果通过上述查询获得的记录很少,则可以按照以下2种方法进行操作-

Approach1: You can either delete these records in child table or insert in master table also and then you can create relationship by this alter command. 方法1:您可以删除子表中的这些记录,也可以在主表中插入,然后可以通过此alter命令创建关系。

Approach2: If you don't want to change in your tables existing data and still want to execute your alter query then use as per below- 方法2:如果您不想更改表中的现有数据,但仍想执行更改查询,请按照以下说明使用-

SET FOREIGN_KEY_CHECKS=0;

ALTER TABLE `Installers` 
    ADD  FOREIGN KEY (`name`) 
         REFERENCES `SOLAR_PV`.`Contacts`(`name`) 
         ON DELETE CASCADE ON UPDATE CASCADE;

SET FOREIGN_KEY_CHECKS=1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM