Вопрос

I have two tables QUESTIONS and QUESTIONS_ATTEMPTED. I am trying to get a list of questions for a TEST_SESSION_ID, and then to output the responses given for questions that were attempted, and null values for those that were not attempted.

The structure of the tables is as follows:

QUESTIONS
    (
        ID
        QUESTION_TEXT
        CORRECT_ANSWER
    )

QUESTIONS_ATTEMPTED
    (
        ID
        QUESTION_ID
        TEST_SESSION_ID
        RESPONSE
    )

I have tried this query but it only returns the questions attempted, not those that were not attempted for that test (due to the WHERE clause):

SELECT      q.ID,
            q.CORRECT_ANSWER,
            qa.RESPONSE
    FROM QUESTIONS q
LEFT JOIN QUESTIONS_ATTEMPTED qa
    ON qa.QUESTION_ID = q.ID
WHERE q.TEST_ID=1 AND qa.TEST_SESSION_ID=235

How could I get a result with all the questions in a given test, whether attempted or not?

Это было полезно?

Решение

You need to move the conditions on the second table into the on clause:

SELECT q.ID, q.CORRECT_ANSWER, qa.RESPONSE
FROM QUESTIONS q LEFT JOIN
     QUESTIONS_ATTEMPTED qa
     ON qa.QUESTION_ID = q.ID and qa.TEST_SESSION_ID = 235
WHERE q.TEST_ID = 1 ;

Otherwise, the value is NULL on the non-matched rows and this fails the comparison.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top