简体   繁体   中英

Cannot Add foreign key constraint to my table

I am trying to set a FK and I am getting an error

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

Is it because Artist isnt a PK in Artists table and can't be used as 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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