【问题标题】:How do i join two tables in such a way that all the rows are present in the output如何以所有行都出现在输出中的方式连接两个表
【发布时间】:2016-06-22 06:38:09
【问题描述】:

我有两个表,表 A 和表 B,结构如下

表A

客户名称
cust_id
cust_age

表B

身份证
cust_id
余额

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

tableA.cust_name,tableA.cust_age,tableB.balance

但是如果我使用下面的查询

select a.cust_name,a.cust_age,sum(b.balance) from tableA a,tableB b where a.cust_id=b.cust_id and b.id = (select max(id) from tableB where cust_id=b.cust_id)

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

【问题讨论】:

  • 我不明白您的编辑。如果您限制b.id = (select max(id)...),那么您将匹配b 上的一行,因此您对一个值求和,这是没有意义的。或者你不会匹配任何行。你真正想做什么?只是获取每个客户的最新余额?如果是这样,那与您最初询问的内容相比,这是一个相当大的变化。

标签: sql oracle


【解决方案1】:

我会说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

【讨论】:

  • ANSI 联接是在 9i 中引入的,因此您必须使用 真正 旧版本才能使用旧的联接表示法。
  • Dom,我已经更新了问题,你能帮我解决这个问题吗
  • 我在答案中的代码应该会给你正确的结果。
猜你喜欢
  • 1970-01-01
  • 2021-07-08
  • 1970-01-01
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多