简体   繁体   English

两列的唯一约束

[英]Unique constraint on two columns

I have a table called QuestionMultipleChoice that has the following structure: 我有一个名为QuestionMultipleChoice的表,该表具有以下结构:

ID int,
QID int,
Text varchar(200),
CorrectAnswer bit

I'm wanting to establish a unique constraint that consists of QID and CorrectAnswer . 我想建立一个由QIDCorrectAnswer组成的唯一约束。 However, I only want to limit where CorrectAnswer is '1'. 但是,我只想限制CorrectAnswer为“ 1”的位置。

CONSTRAINT QuestionMultipleChoice_UC UNIQUE (QuestionID, CorrectAnswer)

If you set CorrectAnswer to null instead of 0, then a unique index on (QID,CorrectAnswer) will only consider rows where CorrectAnswer is 1. 如果将CorrectAnswer设置为null而不是0,则(QID,CorrectAnswer)上的唯一索引将仅考虑CorrectAnswer为1的行。

From the SQL-92 standard 从SQL-92标准

"A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns. In addition, if the unique constraint was defined with PRIMARY KEY, then it requires that none of the values in the specified column or columns be the null value." “当且仅当表中的两行在唯一列中没有相同的非空值时,才满足唯一约束。此外,如果唯一约束是使用PRIMARY KEY定义的,则它不需要指定的一个或多个列为空值。”

You can do this using a Function Based Check Constraint or a Trigger . 您可以使用基于函数的检查约束触发器来执行此操作。

Something like this (I might have missed on the syntax): 像这样的东西(我可能在语法上有所遗漏):

A function that returns the number of correct answers for a question: 该函数返回问题的正确答案的数量:

CREATE FUNCTION CheckAnswer(pQuestionId int)
RETURNS int
AS 
BEGIN
   DECLARE @retval int
   SELECT @retval = COUNT(*) FROM QuestionMultipleChoice c where c.QuestionId = pQuestionId and c.CorrectAnswer = 1
   RETURN @retval
END;

A constraint that uses the function to check whether this question has only one correct answer. 使用该函数检查此问题是否只有一个正确答案的约束。 The check for CorrectAnswer = 0 is for a slight optimization: CorrectAnswer = 0的检查是一个轻微的优化:

ALTER TABLE QuestionMultipleChoice
ADD CONSTRAINT chkAnswer CHECK (CorrectAnswer = 0 OR dbo.CheckAnswer(QuestionId) <= 1);

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

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