SQL - 内部联接

时间:2015-01-11 14:56:36

标签: mysql sql sql-server 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
WHERE t1.behandeltraject = 1 AND t1.meting = 1 AND t1.vragenlijst = 1
AND t2.behandeltraject = 1 AND t2.meting = 1 AND t2.vragenlijst = 2

这将输出的是:

Result of above query

这正是我想要的。

然而,问题是:

如果我添加另一个内连接

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

我的问题:

  1. 我怎样才能检索开头的内容,

  2. 然后将内部联接antwoorden t3添加到其中,但之后添加空值(如果找不到t3.behandeltraject = 1 AND t3.meting = 2 AND t3.vragenlijst = 1的行)?

  3. 说明我的意思:

    Desired result

    而不是返回0条记录。

    非常感谢任何帮助

2 个答案:

答案 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将允许前两个表中的记录返回,无论他们是JOINt3,还是使用WHERE条件过滤记录{ {1}}等等,您将删除结果。将t3.meting = 2条件移至WHERE将返回与初始查询相同的记录,仅添加JOIN的{​​{1}},因为没有符合条件。

答案 1 :(得分:2)

您应该在最后一个中使用LEFT OUTER JOIN而不是INNER JOIN

LEFT JOIN antwoorden t3 ON t1.onderzoeksNR = t3.onderzoeksNR