I have 2 tables
TABLE1 listing all test questions before test.
TABLE 1:
testid qnid qn
1 1 currency of iran
1 2 highest peak
1 3 longest bridge
TABLE 2 listing test responses as status after test for all students :
TABLE 2:
studentid testid qnid status
1 1 1 unanswered
1 1 2 unanswered
2 1 1 unanswered
2 1 2 answered
The TABLE 2 given is incomplete as it does not contain response for all qnid.
The RESULT should be table listing all testid, qnid from TABLE 1 of test with studentid,status from TABLE 2 for the matching testid,qnid for studentid=2
i.e. RESULT:
testid qnid studentid status
1 1 2 unanswered
1 2 2 answered
1 3
TABLE 2 does not contain value for testid=1 qnid=3 from TABLE 1 so its space should be left empty in RESULT table.
The query I used:
select distinct table1.testid,table1.qnid,table2.status
from table1
left outer join table2
on table1.testid = table2.testid
where (table2.studentid = 2
or table2.studentid =NULL)
But instead the output is:
testid qnid status
1 1 unanswered
1 1 answered
1 2 unanswered
1 2 answered
1 3 unanswered
1 3 answered
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `table2` ADD INDEX `table2_idx_testid_studentid` (`testid`,`studentid`);
SELECT
DISTINCT table1.testid,
table1.qnid,
table2.status
FROM
table1
LEFT OUTER JOIN
table2
ON table1.testid = table2.testid
WHERE
(
table2.studentid IN (
2, NULL
)
)