如何以输出中存在所有行的方式连接两个表

时间:2016-03-08 10:47:44

标签: sql oracle

我有两个表,表示TableA和TableB,结构如下

表A

CUST_NAME
CUST_ID
cust_age

表B

ID
CUST_ID
平衡

我需要加入这两个表,检索下面的列

  

tableA.cust_name,tableA.cust_age,tableB.balance

但如果我使用以下查询

  

从tableA a,tableB b中选择a.cust_name,a.cust_age,sum(b.balance)   其中a.cust_id = b.cust_id和b.id =(从tableB中选择max(id),其中cust_id = b.cust_id)

我只获得两个表中存在的那些行,但是我需要tableA中有客户的所有行而不是tableB中的b.balance应该为null或0。

1 个答案:

答案 0 :(得分:2)

我会说Left join

SELECT a.cust_name, a.cust_age, sum(nvl(b.balance,0)) 
FROM tableA a
LEFT JOIN tableB b 
  ON a.cust_id=b.cust_id
GROUP BY a.cust_name, a.cust_age

也可以使用NVL,因为你可能会在b.balance中获得一些空值。

或者,如果您使用的是旧的Oracle版本,则必须使用其他联接:

SELECT a.cust_name, a.cust_age, sum(nvl(b.balance,0)) 
FROM tableA a, tableB b 
where a.cust_id=b.cust_id (+)
GROUP BY a.cust_name, a.cust_age