简体   繁体   中英

Join two tables without having same key in oracle

Suppose I have 2 tables A and B and would like to join those,

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?

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. The NVL function just returns the first argument that isn't null. In this case, if a.id exists, it will be returned. Otherwise, b.id will be. 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. Pop that into a result column named "id", and you'll have what you expect.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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