简体   繁体   English

无法将外键约束添加到我的表中

[英]Cannot Add foreign key constraint to my table

I am trying to set a FK and I am getting an error 我正在尝试设置FK,但出现错误

My datatypes are same as reference table.My Artists table contain all the names and I created another table for artist images. 我的数据类型与参考表相同。我的艺术家表包含所有名称,并且为艺术家图像创建了另一个表。 Tables: 表格:

在此处输入图片说明

ALTER TABLE Artist_Images
    ADD CONSTRAINT FK_Artist_Images_Artist
    FOREIGN KEY (Artist)
    REFERENCES Artists (Artist)

#1215 - Cannot add foreign key constraint #1215-无法添加外键约束

Is it because Artist isnt a PK in Artists table and can't be used as PK? 是否因为Artists不是Artists表中的PK而不能用作PK? Any other suggestions on how can I link the tables? 关于如何链接表的其他建议?

One of the most common reason for not being able to create a foreign key when data exists is that the column in the table you are trying to add the key to has values which do not exist in the referenced table. 数据存在时无法创建外键的最常见原因之一是,您要向其中添加键的表中的列具有所引用表中不存在的值。

In this case, you can check for that by running the following query: 在这种情况下,您可以通过运行以下查询来进行检查:

   SELECT i.Image, i.Artist FROM Artist_Images i
      LEFT JOIN Artists a on i.Artist = a.Artist
      WHERE a.Artist IS NULL

If you get any rows, you need to resolve that before you can create the foreign key. 如果有任何行,则需要先解决该问题,然后才能创建外键。

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

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