简体   繁体   English

在Oracle中没有相同键的情况下联接两个表

[英]Join two tables without having same key in oracle

Suppose I have 2 tables A and B and would like to join those, 假设我有2个表A和B,并且想加入它们,

A:
---------------
id   |  name  |
---------------
1    |  jack  |
2    |  hanna |
3    |  jack  |
4    |  hanna |

B:
---------------
id   | status |
---------------
1    | online |
3    | offline|
5    |  away  |

How can I join these two tables to get a output like the following, 我如何连接这两个表以得到如下输出,

-----------------------
id   |  name  |  Status
-----------------------
1    |  jack  |  online 
2    |  hanna |  (null)
3    |  jack  |  offline
4    |  hanna |  (null)
5    | (null) |  away

I have tried outer join like 我已经尝试过像

A.id = B.id(+) 

It only shows the entries where only A.id exist, but how to get all records from both A and B? 它仅显示仅存在A.id的条目,但如何从A和B获取所有记录?

This is called a full outer join : 这称为完全外部联接

SELECT NVL(a.id, b.id) as id, a.name, b.status
FROM A a FULL OUTER JOIN B b ON (a.id = b.id)

To avoid two id columns, or an id column that might be NULL, use NVL. 为避免使用两个id列或一个可能为NULL的id列,请使用NVL。 The NVL function just returns the first argument that isn't null. NVL函数仅返回不为空的第一个参数。 In this case, if a.id exists, it will be returned. 在这种情况下,如果a.id存在,它将被返回。 Otherwise, b.id will be. 否则,b.id将是。 Since one of the two columns must not be null (and they'll always match if they don't exist), this will always return the right id. 由于两列之一不得为null(如果不存在,它们将始终匹配),因此这将始终返回正确的ID。 Pop that into a result column named "id", and you'll have what you expect. 将其弹出到名为“ id”的结果列中,您将获得期望的结果。

select a.id, a.name, b.status
from a 
full outer join b on a.id = b.id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM