2012-03-02 71 views
0

我的数据库设计有问题。 我心里有两个选择,但他们没有真正解决我的问题:用不同答案数据类型的许多问题的数据库设计

选项1:

FB (ID, Year, Question, Value) 
    1 | 2004| Q1  | hello 
    1 | 2004| Q2500 | 15.2.12 
    1 | 2004| Q2  | 56€ 
    1 | 2003| Q1  | bye 
    2 | 2003| Q2  | 55€ 

问题与选项1是该领域的“价值”的数据类型可以是真是应有尽有!为了解决这个问题,我认为

  1. 创建为每个数据类型或表
  2. 改变表FB(ID,年份,问题,Valueint,的valueString,... .etc。)

1.和2.都不适合我。

选项2:

FB (ID, Year, Q1, Q2, …., Q2500) 
    1| 2004 | hello| 56€ |,....,| 15.2.12 
    1| 2003 | bye | …...|,….., |….. 
    2| 2003 | salut| 55€ |, …..,|…..  

问题的(Q1-QX)的数量可以有很大的差异。

任何建议表示赞赏!谢谢...

+0

欢迎来到StackOverflow:如果您发布代码,XML或数据样本,**请**在文本编辑器中突出显示这些行,然后单击编辑器工具栏上的“代码示例”按钮(“{}”)格式和语法突出显示它! – 2012-03-02 09:12:25

回答

2

我会去

CREATE TABLE Questions (
    QuestionID varchar(5) not null primary key, 
    AnswerType varchar(10) not null, 
    constraint CK_Question_Types CHECK (AnswerType in ('INT','CHAR','BOOL')), --Add more appropriate type names 
    constraint UQ_Questions_TypeCheck UNIQUE (QuestionID,AnswerType) 
) 

和:

CREATE TABLE Answers (
    ID int not null, 
    Year int not null, 
    QuestionID varchar(5) not null, 
    AnswerType varchar(10) not null, 
    IntAnswer int null, 
    CharAnswer varchar(max) null, 
    BoolAnswer bit null, 
    constraint FK_Answers_Questions FOREIGN KEY (QuestionID) references Questions, 
    constraint FK_Answers_Question_TypeCheck FOREIGN KEY (QuestionID,AnswerType) references Questions (QuestionID,AnswerType), 
    constraint CK_Answer_Types CHECK (
     (IntAnswer is null or AnswerType='INT') and 
     (CharAnswer is null or AnswerType='CHAR') and 
     (BoolAnswer is null or AnswerType='BOOL') and 
     (IntAnswer is not null or CharAnswer is not null or BoolAnswer is not null) 
    ) 
) 

这使您可以确保每个答案是正确的类型,并且不为空,同时确保没有多余的数据在表格中结束。


使用两个外键是不是真的需要(你可以删除FK_Answers_Questions),但我更愿意记录,真正的FK引用是QuestionID,同时我们要加强跨约束表,使用第二个和新的约束。

0

我将创建两个表:

Create Table tblQuestions (
    ID int IDENTITY(1,1) NOT NULL, 
    Year varchar(4) Default '', 
    QuestionText varchar(4000) Default '', 
    AnswerDataType varchar(50) Default '') 

Create Table tblAnswers (
    ID int IDENTITY(1,1) NOT NULL, 
    tblQuestions_ID int Default 0, 
    Answer varchar(255) Default '') 

然后,我会创建一个函数或存储过程来验证答案是在正确的数据类型给出返回TRUE或FALSE。不幸的是,我没有时间写这些代码。