我不确定如何准确地说出这一点,因为我刚刚启动了SQL并且刚刚完成了简单的连接。
首先从我的桌子开始:
tblQuestions
| Survey ID | User ID | Entry Date | Question 1 | Question 2 | Question 3 | Question 4 | | 1 | 305 | date | 0 | 1 | 2 | 3 |
tblValues
| VID | TextValue | | 0 | Never | | 1 | Rarely | | 2 | Sometimes | | 3 | Often |
我想要一个SQL查询,它输出每个问题VID的TextValues。 我无法直接存储文本值,因为数据将导出为图表。此外,我从我所理解的重复数据是糟糕的表设计和规则何时规范化表。
这可以通过单个查询吗?
编辑:我正在使用MS Access。 期望的输出:
| Survey ID | User ID | Entry Date | Question 1 | Question 2 | Question 3 | Question 4 | | 1 | 305 | date | Never | Rarely | Sometimes | Often |
答案 0 :(得分:2)
您想要将一个调查记录与四个答案记录连接起来,因此您必须四次查询答案表。使用表别名来区分四个记录:
select
q.survey_id, q.user_id, q.entry_date,
v1.textvalue, v2.textvalue, v3.textvalue, v4.textvalue
from tblQuestions q
join tblValues v1 on v1.vid = q.question1
join tblValues v2 on v2.vid = q.question2
join tblValues v3 on v3.vid = q.question3
join tblValues v4 on v4.vid = q.question4;
更新:正如克里斯指出的那样,Access还有一些额外的加入要求。因此,上述标准SQL查询必须进行修改:
select
q.survey_id, q.user_id, q.entry_date,
v1.textvalue, v2.textvalue, v3.textvalue, v4.textvalue
from (((tblQuestions q
inner join tblValues as v1 on v1.vid = q.question1)
inner join tblValues as v2 on v2.vid = q.question2)
inner join tblValues as v3 on v3.vid = q.question3)
inner join tblValues as v4 on v4.vid = q.question4;
答案 1 :(得分:0)
就像一个开始:
CREATE TABLE Survey(ID INT NOT NULL IDENTITY CONSTRAINT PK_Survey PRIMARY KEY
,BeginOfSurvey DATETIME NOT NULL);
CREATE TABLE Value(ID INT NOT NULL IDENTITY CONSTRAINT PK_Value PRIMARY KEY
,Caption VARCHAR(100) NOT NULL);
CREATE TABLE QuestionText(ID INT NOT NULL IDENTITY CONSTRAINT PK_QuestionText PRIMARY KEY
,Caption VARCHAR(100) NOT NULL);
CREATE TABLE Question(ID INT NOT NULL IDENTITY CONSTRAINT PK_Question PRIMARY KEY
,SurveyID INT NOT NULL CONSTRAINT FK_Question_SurveyID FOREIGN KEY REFERENCES Survey(ID)
,QuestionTextID INT NOT NULL CONSTRAINT FK_Question_QuestionTextID FOREIGN KEY REFERENCES QuestionText(ID)
,ValueID INT NOT NULL CONSTRAINT FK_Question_ValueID FOREIGN KEY REFERENCES Value(ID));
INSERT INTO Value VALUES
('Never')
,('Rarely')
,('Sometimes')
,('Often');
INSERT INTO QuestionText VALUES
('Do you smoke?')
,('Do you drink alcohol?');
INSERT INTO Survey VALUES(GETDATE());
INSERT INTO Question VALUES
(1,1,2)
,(1,2,3);
SELECT *
FROM Survey AS s
INNER JOIN Question AS q ON s.ID=q.SurveyID
INNER JOIN QuestionText AS qt ON qt.ID=q.QuestionTextID
INNER JOIN Value AS v ON v.ID=q.ValueID