简体   繁体   中英

SQL select statement issue

I'm facing a SQL SELECT problem:

There is a question, this question has an anwser, and this answer has a next question, and so on... This is my query:

SELECT Q.question, A.answer, A.nextQuestion as 'next question' from answers A join questions Q on A.nextQuestion = V.questionId 
order by Q.question;

This is the output of the above query:

Question 1 | Answer 1 | 2
Question 1 | Answer 2 | 2
Question 2 | Answer 1 | 1
Question 2 | Answer 2 | 1

So right now the 'next question' is a number... But I'd like to resolve that number to the next question text (Q.question)... How can I achieve this?

I want something like this:

Question 1 | Answer 1 | Question 2
Question 1 | Answer 2 | Question 2
Question 2 | Answer 1 | Question 1
Question 2 | Answer 2 | Question 1

Thanks in advance!!

I'm working with MySQL.

This is my table structure:

Table "Questions"

+------------------+
| Field            |
+------------------+
| questionId       |
| question         |
+------------------+

Table "Answers"

+------------------+
| Field            |
+------------------+
| answerId         |
| answer           |
| nextQuestion     |
+------------------+

Your data structure is missing a link from a question to answer.

So, I'm going to postulate the answers has a field QuestionId as well as NextQuestionId . This is one way that you get the link you need. If you don't have such a link, then you need to think some more about your data structure.

With such a field, a second join to questions gets what you need:

SELECT Q.question, A.answer, nextq.Question as 'next question'
from questions Q
     answers A join
     on A.QuestionId = q.questionId join
     questions nextq
     on A.NextQuestionId = nextq.QuestionId
order by Q.question;

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