Skip to content
Advertisement

SQL query to get data of MCQ question and the answer from two table

MCQ Question and correct answer table name = Table1

Options for every MCQ question and options code table Name = Table2

Table1

enter image description here

Table2

enter image description here

SQL query to get data in the form of –

Questions, All 3 options and correct option

Advertisement

Answer

I am assuming you are using MSSQL as database

Use JOINS

FIDDLE DEMO

SELECT Q.ID, Q.Que Quetion, A.Choice Options, Op.Choice AS Answer
FROM Table1 Q JOIN Table2 A ON Q.Id= A.Id
LEFT JOIN Table2 Op ON Q.ID = Op.Id AND Q.Ans_Id = Op.Choice_Id

Or

SELECT Q.ID, Q.Que Quetion, A.Choice Options, Op.Choice AS Answer
FROM Table1 Q JOIN Table2 A ON Q.Id= A.Id
LEFT JOIN Table2 Op ON Q.ID = Op.Id AND Q.Ans_Id = Op.Choice_Id 
                   AND Op.Choice_Id = A.Choice_Id 

Output

ID  Quetion             Options      Answer
1   Sample Question #1  (a) sasas   (a) sasas
1   Sample Question #1  (b) saewew  (a) sasas
1   Sample Question #1  (c) 4234    (a) sasas
2   Sample Question #2  (a) xxxxx   (c) sd4234
2   Sample Question #2  (b) 5855sz  (c) sd4234
2   Sample Question #2  (c) sd4234  (c) sd4234
3   Sample Question #3  (a) bbbbbb  (b) saew34
3   Sample Question #3  (b) saew34  (b) saew34
3   Sample Question #3  (c) 42d34   (b) saew34
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement