The INSERT statement conflicted with the FOREIGN KEY constraint. The conflict occurred in database

六眼飞鱼酱① 提交于 2019-12-19 08:56:36

问题


I have been having this problem for a couple of hours now. In SQL Server, I ran this query :

INSERT INTO USERS_AVATAR(userId, avatId) VALUES ('1', '213');
INSERT INTO USERS_AVATAR(userId, avatId) VALUES ('2', '312');

but the message shows up saying :

Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FKUSERS_AVAT731248". The conflict occurred in database "gk314", table "gk314.USERS", column 'userId'.

Msg 547, Level 16, State 0, Line 2
The INSERT statement conflicted with the FOREIGN KEY constraint "FKUSERS_AVAT731248". The conflict occurred in database "gk314", table "gk314.USERS", column 'userId'.

Help please!


回答1:


Before inserting userIds 1 and 2 into USERS_AVATAR, you must first insert them into table USERS. That is what the FOREIGN KEY constraint is requiring.




回答2:


Foreign key constraints are SQL's way of saying "this table expects data to exist in other tables". It allows you to reference other tables without the data having to exist twice or to be kept in sync.

In this case, there's a table for user data (USERS) and a table for avatar data (AVATARS), and the USERS_AVATAR table links the two together. You will need to add a user to the users table, then an avatar to the avatar table, then you can link the two together. It will look something like this:

INSERT INTO USERS (userId, email, password, status) VALUES (1, 'gk314@hotmail.com',' gk314', 'strong')
INSERT INTO AVATARS (avatId, name, ...) VALUES (1, 'Avatar1', ...)
INSERT INTO USERS_AVATAR (userId, avatId) VALUES (1, 1)

Original Answer:

This means that there's a table, gk314.USERS, that doesn't have a userId that matches the userId you're attempting to add to USERS_AVATAR. Check the USERS table and add users with userId 1 and 2, and then you should be able to add to the USERS_AVATAR table.



来源:https://stackoverflow.com/questions/29235773/the-insert-statement-conflicted-with-the-foreign-key-constraint-the-conflict-oc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!