外部约束键

时间:2017-02-13 09:33:07

标签: mysql sql foreign-keys foreign-key-relationship

我尝试在表review_id中的字段Reviews与表id中的Sentences之间创建外键。表格的结构如下:

CREATE TABLE `Reviews` (
  `review_id` varchar(255) CHARACTER SET utf8 NOT NULL,
  `package_name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `review_content` text CHARACTER SET utf8,
  `review_date` date DEFAULT NULL,
  `star_rating` int(11) DEFAULT NULL,
  `app_version_id` int(11) NOT NULL,
  PRIMARY KEY (`review_id`),
  KEY `app_version_id` (`app_version_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `Sentences` (
  `id` varchar(255) NOT NULL DEFAULT '',
  `review` text,
  `category` varchar(255) DEFAULT NULL,
  `topic` varchar(255) DEFAULT NULL,
  KEY `rev-id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我面临以下错误,我不明白问题所在。

ALTER TABLE `Reviews` ADD CONSTRAINT `rev-to-sents` FOREIGN KEY (`review_id`) REFERENCES `Sentences` (`id`)
Foreign key constraint fails for table `msr test db`.`#sql-75_d`:
,
  CONSTRAINT `rev-to-sents` FOREIGN KEY (`review_id`) REFERENCES `Sentences` (`id`)

尝试在索引PRIMARY元组中添加子表:     DATA TUPLE:8个字段;      0:len 36; hex 37626532323335652d616663392d313165362d383935342d633462333031636466363237; asc 7be2235e-afc9-11e6-8954-c4b301cdf627 ;;     ...

2 个答案:

答案 0 :(得分:2)

问题听起来像是在尝试添加不匹配行的外键。如果是这样,您的第一个任务是查找不匹配的行并确定问题的范围换句话说,您遇到public partial class DeviceType { public DeviceType() { this.Devices = new HashSet<Devices >(); } public int Id { get; set; } public string Name { get; set; } public bool Active { get; set; } public string Code { get; set; } public virtual ICollection<Device> Devices { get; set; } } public override ICollection<DeviceType> Get() { return DbContext.Set<DeviceType>().ToList().Select(x => new DeviceType { Id = x.Id, Name = x.Name }).ToList(); } Reviewes.review_id

中的任何值都不匹配的情况

您需要先找到并修复数据。这意味着:

Sentences.id

由于SELECT review_id FROM Reviews LEFT JOIN Sentences ON review_id = Sentences.id WHERE Sentences.id IS NULL; 上有NOT NULL约束,只有当连接条件失败时,id才会为空。

答案 1 :(得分:0)

试试这个:

ALTER TABLE Reviews
ADD CONSTRAINT rev-to-sents
ADD FOREIGN KEY (review_id)
REFERENCES Sentences (id)