AT-2016 AT-2016 - 1 year ago 75
SQL Question

Matched Rows From Two Table and Display Them As New Row

Suppose, I've data in a table say Table 1 as follows:

QuesID QuesName
1 Question 1
2 Question 2
3 Question 3
4 Question 4


In Table 2, as follows:

ID QuesID MainQuesID
1 4 1
2 2 2


I want to have the following output:

QuesID QuesName
1 Question 1
1 Question 4
2 Question 2
2 Question 2
3 Question 3
4 Question 4


Is it actually possible to do with Sql? I tried the following but it will return all the questions even if it does not match the ID (Order by MainQuesID):

SELECT m.QuesID
, m.QuesName
FROM Table_1 m
GROUP
BY m.QuesID
,m.QuesName
UNION ALL
SELECT k.QuesID
, m.QuesName
FROM Table_2 k

Answer Source

I assume, from the result you posted, that entries from the Table_2 are to be listed by their MainQuesID.

SELECT * from 
    ((SELECT t1.qstnID as QuesID, t1.Title as QuesName FROM Table_1 t1)
    UNION (SELECT t2.mainqstnID as QuesID, t2.Title as QuesName FROM Table_2 t2))
    as union_table
    ORDER BY union_table.QuesID

This projects both tables into the Format (QuesID, QuesName), then unions them, then orders them by ID.