我的查询如下:
SELECT t1.onderzoeksNR, t1.antwoorden as b1_m1_v1_items, t1.commentaar as b1_m1_v1_toe, t2.antwoorden as b1_m1_v2_items, t2.commentaar as b1_m1_v2_toe
FROM antwoorden t1
INNER JOIN antwoorden t2
ON t1.onderzoeksNR = t2.onderzoeksNR
WHERE t1.behandeltraject = 1 AND t1.meting = 1 AND t1.vragenlijst = 1
AND t2.behandeltraject = 1 AND t2.meting = 1 AND t2.vragenlijst = 2
这将输出的是:
这正是我想要的。
然而,问题是:
如果我添加另一个内连接
inner join antwoorden t3
on t1.onderzoeksNR = t3.onderzoeksNR
但是喜欢:
t3.behandeltraject = 1 AND t3.meting = 2 AND t3.vragenlijst = 1
查询将返回0条记录。
显然,这是因为antwoorden
中包含所询问属性的无行。
(t3.behandeltraject = 1 AND t3.meting = 2 AND t3.vragenlijst = 1
)
我的问题:
我怎样才能检索开头的内容,
然后将内部联接antwoorden t3
添加到其中,但之后添加空值(如果找不到t3.behandeltraject = 1 AND t3.meting = 2 AND t3.vragenlijst = 1
的行)?
说明我的意思:
而不是返回0条记录。
非常感谢任何帮助
答案 0 :(得分:3)
您需要LEFT JOIN
,并且需要将一些WHERE
条件移至JOIN
条件:
SELECT t1.onderzoeksNR, t1.antwoorden as b1_m1_v1_items, t1.commentaar as b1_m1_v1_toe, t2.antwoorden as b1_m1_v2_items, t2.commentaar as b1_m1_v2_toe
FROM antwoorden t1
INNER JOIN antwoorden t2
ON t1.onderzoeksNR = t2.onderzoeksNR
LEFT JOIN antwoorden t3 ON t1.onderzoeksNR = t3.onderzoeksNR
AND t3.behandeltraject = 1 AND t3.meting = 2 AND t3.vragenlijst = 1
WHERE t1.behandeltraject = 1 AND t1.meting = 1 AND t1.vragenlijst = 1
AND t2.behandeltraject = 1 AND t2.meting = 1 AND t2.vragenlijst = 2
LEFT JOIN
将允许前两个表中的记录返回,无论他们是JOIN
到t3
,还是使用WHERE
条件过滤记录{ {1}}等等,您将删除结果。将t3.meting = 2
条件移至WHERE
将返回与初始查询相同的记录,仅添加JOIN
的{{1}},因为没有符合条件。
答案 1 :(得分:2)
您应该在最后一个中使用LEFT OUTER JOIN
而不是INNER JOIN
:
LEFT JOIN antwoorden t3 ON t1.onderzoeksNR = t3.onderzoeksNR