MySQL Join Return Null

时间:2012-12-04 09:15:56

标签: mysql join left-join union-all

我有两张桌子

Table_1
id|subject_code|subject_id
 1|Test1       |1
 2|Test2       |2
 3|Test3       |3

Table2
id|subject_id|grade|status
 1|1         |5.00 |Fail
 2|3         |2.25 |Pass

现在,我想创建一个将返回以下内容的查询

Table3
subject_code|grade|status
Test1       |5.00 |Fail
Test2       |NULL |NULL
Test3       |2.25 |Pass

我已经读过关于将左连接和联合组合在一起的所有内容,但我对如何做到这一点感到很遗憾。 提前谢谢。

3 个答案:

答案 0 :(得分:4)

尝试左连接,例如::

Select 
DISTINCT(table1.subject_code), 
grade, 
status

from table1 
LEFT join table2 on (table1.subject_id=table2.subject_id)

答案 1 :(得分:4)

SELECT subject_code, grade, status 
FROM Table_1 t1 
LEFT JOIN Table2 t2 ON t1.subject_id = t2.subject_id;

答案 2 :(得分:1)

我想一个简单的LEFT JOIN可以解决这个问题:

SELECT Table_1.subject_code, Table2.grade, Table2.status FROM Table_1 LEFT JOIN Table2 ON Table2.subject_id = Table_1.subject_id;