简体   繁体   中英

Query to retrieve main records in one table and its all sub records from another table

Let us suppose we have tables like questions and answers

Questions table

qno question
1   first question
2   second question

Answers table

ano qno answer
1   1   first answer for q1
2   1   second answer for q1
3   2   first answer for q2
4   1   third answer for q1
5   2   second answer for q2

Now I need a single query in mysql that can output each question and all of its answers

Expected output

qno ano    question                      answer
--- ---    ----------                   -------------------
1    0   first question                   
1    1                                  first answer for q1
1    2                                  second answer for q1
1    4                                  third answer for q1
2    0   second question                
2    3                                  first answer for q2
2    5                                  second answer for q2

Normally a JOIN doesn't output results in the format you show as your desired result. The JOIN operator in SQL matches rows from one table to rows from the other, so it will produce the question repeatedly, which is not what you want.

To get what you want, use UNION instead of JOIN , and position them into columns like you want:

(SELECT qno, 0, question, NULL AS `answer` FROM questions)
UNION
(SELECT qno, ano, NULL, answer FROM answers)
ORDER BY qno, ano

For what it's worth, I agree with the comments from Strawberry. I wouldn't actually do this in my application. I would fetch the data in a simpler format, and in my application code present the data in the layout desired.

My example above is only to show that manipulating the data into that layout in SQL makes the code less clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM