微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

工作台进行外键约束时出错

如何解决工作台进行外键约束时出错

我制作的数据库MysqL Workbrench中的两列组成。我将数据从.csv导入到sql。列的结构为: 表“气体”

CREATE TABLE `gases` (
  `site_gaw_id` text,`year` int(11) DEFAULT NULL,`month` int(11) DEFAULT NULL,`day` int(11) DEFAULT NULL,`value` double DEFAULT NULL,`ID_station` int(11) NOT NULL,`name_of_value` text,KEY `ID_station` (`ID_station`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

表台_2

CREATE TABLE `stations_2` (
  `ID_stations` int(11) NOT NULL,`Name` text,`Type` text,`Country` text,`Latitude` double DEFAULT NULL,`Longitude` double DEFAULT NULL,`elevation` int(11) DEFAULT NULL,`site_gaw_id` text,`stations_id` int(11) DEFAULT NULL,PRIMARY KEY (`ID_stations`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

我想在工作台中建立两列之间的关系。该关系应通过“ ID_station”来实现。

因此,我需要进行外键约束。在工作台中,我写道:

ALTER TABLE `gases_db`.`gases` 
ADD CONSTRAINT `id_station_fk`
  FOREIGN KEY (`ID_station`)
  REFERENCES `gases_db`.`stations_2` (`ID_stations`)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

结果我得到了一个错误

Operation Failed: There was an error while applying the sql script to the database.
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`gases_db`.`#sql-3b5_a`,CONSTRAINT `id_station_fk` FOREIGN KEY (`ID_station`) REFERENCES `stations_2` (`ID_stations`) ON DELETE CASCADE ON UPDATE CASCADE)
sql Statement:

我应该如何解决我的问题?

解决方法

表中有些行未通过外键验证。也就是说,您在id_station中有一些gases在表id_stations的列stations_2中找不到。

您可以使用以下查询来显示有问题的行:

select *
from gases g
where not exists (select 1 from stations_2 s where s.id_stations = g.id_station)

您需要修复表gases中的错误数据(通过将id_station更新为有效值或删除该行)。当查询不返回任何行时,您就会知道可以创建外键。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。