在sql

时间:2016-03-18 20:30:04

标签: sql sql-server tsql

我有两个表QuestionsAnswers,分别存储多项选择题和4个可能的答案。我试图一次插入一个问题及其4个答案。

The INSERT statement conflicted with the FOREIGN KEY constraint .... "dbo.Answers", column 'AnswerID'.

The INSERT statement conflicted with the FOREIGN KEY constraint  table "dbo.Questions", column 'QuestionID'.

以下是我的表格:

CREATE TABLE [dbo].[Questions] (    
    [QuestionID] INT           IDENTITY (1, 1) NOT NULL PRIMARY KEY,
    [HistID]     INT           NOT NULL,
    [Question]   NCHAR (300)   NOT NULL,
    [AnswerID]   CHAR          NOT NULL,
    FOREIGN KEY (AnswerID) REFERENCES [dbo].Answers (AnswerID),
    FOREIGN KEY (HistID) REFERENCES [dbo].HistoricalEvents (HistID)
);

CREATE TABLE [dbo].[Answers] (
    [QuestionID] INT         NOT NULL,
    [AnswerID]   CHAR        NOT NULL,
    [Choice]     NCHAR (200) NOT NULL,
    FOREIGN KEY (QuestionID) REFERENCES [dbo].[Questions] (QuestionID), 
    PRIMARY KEY ([AnswerID])
);

这些是我正在尝试的插页:

INSERT INTO Questions (HistID, Question, AnswerID)
VALUES (
2,
'A major cause of the growth of state and Federal highway systems after World War II was the ___',
'C'
)

Declare @QuestionID INT = SCOPE_IDENTITY()


INSERT INTO Answers(QuestionID, AnswerID, Choice)
VALUES 
(
@QuestionID,
'A',
'increased use of mass transit systems'
),

(
@QuestionID,
'B',
'growing prosperity of inner-city areas'
),

(
@QuestionID,
'C',
'rapid development of suburbs'
),

(
@QuestionID,
'D',
'return of city dwellers to farm areas'
)

预期输出: 我想要上面的命令(或它应该改变的内容)对表进行以下更改:

Questions:
QuestionID   HistID   Question                 AnswerID
--------------------------------------------------------
    1          2      "A major cause of the...    C     

Answers:
QuestionID   AnswerID   Choice
--------------------------------
    1          A         increased use of mass transit systems
    1          B         growing prosperity of inner-city areas
    1          C         rapid development of suburbs
    1          D         return of city dwellers to farm areas

1 个答案:

答案 0 :(得分:4)

您已完成所谓的循环引用。您在问题中将Answers作为FK,在答案表中将Question作为FK。在这里你已经在彼此的桌子上放置了约束。所以你不能插入,因为在插入过程中不存在两个。

这应该是:

  

问题--->答案[QuestionId]仅限FK

这里有一个提示来纠正您的架构:

问题表 -

+------------+
| QuestionId | (PK, int)
+------------+
| HistID     | (FK, int)
+------------+
| Question   | 
+------------+

AnswerTable(可用选项) -

+------------+
| AnswerId   | (PK, int)
+------------+
| Choice     | (char) -- A, B, C, D etc.
+------------+
| Answer     | (nvarchar(100)) -- limit depends on your choice
+------------+
| QuestionId | (FK, int) -- 1 to many relationship means 1 question can have multiple answers choice.
+------------+

正确答案(选择)地图表(两者都是FK将是复合键) -

+------------+
| AnswerId   | (FK, int)
+------------+            |--- composite primary key, 1-1 relationship means 1 question have only one correct choice.
| QuestionId | (FK, int)
+------------+

请参阅 - SQL FIDDLE DEMO显示实施中的想法。