Skip to content
Advertisement

SQL Query creation with multiple joins

I am working with MYSQL, and want to create a query. I have 3 tables.

QUESTION
QUESTION_NUMBER QUESTION_DESCRIPTION
1 anydesc
2 anydesc2
ANSWER
ANSWER_NUMBER ANSWER_DESCRIPTION
1 anydescANS
2 anydesc2ANS
3 anydesc3ANS

And a bridge TABLE

QUESTION_ANSWER
Q_NUM A_NUM
1 1
2 2
2 3

Now I want to retrieve all the Answers of let’s say a specific QUESTION NUMBER i.e 1.

What I have tried.

SELECT QUESTION.QUESTION_NUMBER, QUESTION.QUESTION_DESCRIPTION, ANSWER.ANSWER_NUMBER, ANSWER.ANSWER_DESCRIPTION

FROM QUESTION
RIGHT JOIN QUESTION_ANSWER ON QUESTION.QUESTION_NUMBER=4

INNER JOIN ANSWER ON QUESTION_ANSWER.Q_NUM=4

and similar queries, but I can not make sense of it, and can not get desired output.

What I want is to get all the answers that belong to specific Question Number.

Advertisement

Answer

I would write it this way:

SELECT 
  Q.QUESTION_NUMBER, 
  Q.QUESTION_DESCRIPTION, 
  A.ANSWER_NUMBER, 
  A.ANSWER_DESCRIPTION
FROM QUESTION AS Q
INNER JOIN QUESTION_ANSWER AS QA ON Q.QUESTION_NUMBER = QA.Q_NUM
INNER JOIN ANSWER AS A ON QA.A_NUM = A.ANSWER_NUMBER
WHERE Q.QUESTION_NUMBER=4;

You don’t need RIGHT OUTER JOIN, you need INNER JOIN, because there is certain to be a matching question if you are seeking answers.

I recommend avoiding the “comma-style” join syntax. That was made obsolete in 1989. It works the same as inner join, but it’s worth using the modern syntax consistently.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement