如何从该联接中获取`NULL`数据?

时间:2018-11-28 09:51:50

标签: mysql sql join

我想加入两个表:

t_act
ID_ACT   ACT
1        ACT1
2        ACT2
3        ACT3
4        ACT4
5        ACT5

t_work
NO   ID_WORK   ID_ACT   ACT
1         A         1   ACT1
2         A         3   ACT3

我想要的输出是:

NO    ID_WORK    ID_ACT    ACT
1           A         1    ACT1
2           A         2    NULL
3           A         3    ACT3
3           A         4    NULL
4           A         5    NULL

我使用了LEFT或RIGHT JOIN,但是没有产生想要的输出。

我的查询: SELECT * FROM t_work LEFT OUTER JOIN t_act ON t_work.ID_ACT = t_act.ID_ACT

1 个答案:

答案 0 :(得分:0)

看起来不错:

mysql> select * from t_act;
+--------+------+
| ID_ACT | ACT  |
+--------+------+
|      1 | ACT1 |
|      2 | ACT2 |
|      3 | ACT3 |
|      4 | ACT4 |
|      5 | ACT5 |
+--------+------+
5 rows in set (0.00 sec)

mysql> select * from t_work;
+----+---------+--------+------+
| NO | ID_WORK | ID_ACT | ACT  |
+----+---------+--------+------+
|  1 | A       |      1 | ACT1 |
|  2 | A       |      3 | ACT3 |
+----+---------+--------+------+
2 rows in set (0.00 sec)

输出:

mysql> select a.NO,a.ID_WORK, b.ID_ACT, a.ACT from t_act as b left     
join t_work as a using  (ID_ACT) order by ID_ACT;
+------+---------+--------+------+
| NO   | ID_WORK | ID_ACT | ACT  |
+------+---------+--------+------+
|    1 | A       |      1 | ACT1 |
| NULL | NULL    |      2 | NULL |
|    2 | A       |      3 | ACT3 |
| NULL | NULL    |      4 | NULL |
| NULL | NULL    |      5 | NULL |
+------+---------+--------+------+
5 rows in set (0.02 sec)

但是我不确定所需输出中的NO和ID_WORK列。

ID_ACT 2在表t_work中不存在。因此,您也将在所需输出的NO / ID_WORK列下具有NULL。您确定,这些列上将有VALUES吗?