2017-03-08 86 views
0

在sql server 2014中工作。想問一答管理應用程序。我的應用程序有波紋管表結構。進入sql查詢如何選擇模板1的問題和答案。有沒有更好的方法,請與我分享。如何選擇多個表中的列匹配值

enter image description here

示例演示輸入是:

GO 
INSERT [dbo].[tblQuestionAns] ([QuestionAnsId], [Question], [Ans]) VALUES (1, N'Hello?', N'Hello') 
GO 
INSERT [dbo].[tblQuestionAns] ([QuestionAnsId], [Question], [Ans]) VALUES (2, N'World?', N'World') 
GO 
INSERT [dbo].[tblQuestionAns] ([QuestionAnsId], [Question], [Ans]) VALUES (3, N'Animal?', N'Animal') 
GO 
INSERT [dbo].[tblQuestionAns] ([QuestionAnsId], [Question], [Ans]) VALUES (4, N'Ocean?', N'Ocean') 
GO 
INSERT [dbo].[tblQuestionAns] ([QuestionAnsId], [Question], [Ans]) VALUES (5, N'Human?', N'Human') 
GO 
INSERT [dbo].[tblQuestionTemplate] ([QuestionTemplateId], [Q1], [Q2], [Q3], [Q4], [Q5]) VALUES (1, 1, 3, 5, 4, 2) 
GO 
INSERT [dbo].[tblQuestionTemplate] ([QuestionTemplateId], [Q1], [Q2], [Q3], [Q4], [Q5]) VALUES (2, 1, 5, 3, 2, 4) 
GO 

回答

0

不要想以下結果?

SELECT tt.QuestionTemplateId,qa.Question,qa.Ans FROM tblQuestionTemplate AS tt 
CROSS APPLY (VALUES(Q1),(Q2),(Q3),(Q4),(Q5)) c(Q) 
INNER JOIN tblQuestionAns AS qa ON qa.QuestionAnsId=c.Q 
 
QuestionTemplateId Question Ans 
1 Hello? Hello 
1 Animal? Animal 
1 Human? Human 
1 Ocean? Ocean 
1 World? World 
2 Hello? Hello 
2 Human? Human 
2 Animal? Animal 
2 World? World 
2 Ocean? Ocean 
相關問題