我有两个表格如下所示:
teamid teamname description
1 x abcd
2 y dcba
3 z sadf
stageid teamid responses score
1 1 r1 20
1 2 r2 30
2 1 r4 20
2 2 r5 20
2 3 r6 20
我正在尝试根据我拥有的stageid
号码加入上述两个表格。所以,我尝试了以下内容:
SELECT t1.teamid, t1.teamname, t2.responses, t2.score
FROM table_one as t1
JOIN table_two as t2 ON t1.teamid = t2.teamid
WHERE stageid = 1
这给了我以下结果(我尝试了左,右,内,外连接的所有组合):
teamid teamname responses score
1 x r1 20
2 y r2 30
teamid teamname responses score
1 x r1 20
2 y r2 30
3 z NULL 0
正如您在上面的预期表中所看到的,我想要table_one
和table_two
的所有行,如果数据不存在,我需要NULL
或0
作为值。
怎么做?
答案 0 :(得分:3)
试试这个:
SELECT t1.teamid, t1.teamname, t2.responses, t2.score
FROM table_one as t1
LEFT JOIN table_two as t2 ON t1.teamid = t2.teamid
WHERE stageid = 1 OR stageid IS NULL
默认情况下,当您使用左连接时,没有任何内容可以加入字段以包含NULL,因此您必须添加NULL而不仅仅是特定的stageid。
或者像其他人一样,你可以设置这样的舞台:
SELECT t1.teamid, t1.teamname, t2.responses, t2.score
FROM table_one as t1
LEFT JOIN table_two as t2 ON t1.teamid = t2.teamid AND stageid = 1
WHERE 1
在此查询中,您使用联接的ON标记来设置stageid,并获得相同的结果。 (WHERE 1
没有必要)
答案 1 :(得分:2)
如果您还想检索不匹配的记录,请使用LEFT JOIN
代替INNER JOIN
。
<强>查询强>
select t1.teamid, t1.teamname, t2.responses, coalesce(t2.score, 0) as score
from table_one t1
left join table_two t2
on t1.teamid = t2.teamid
and t2.stageid = 1;