将关系数据行粘合在一起

时间:2017-03-24 17:47:48

标签: sql oracle rdbms

我有一个稀疏表,结构如下:

id | name      | phone          | account   

没有主键或索引

还有空值。我想要的是"胶水"来自不同行的数据,例如: 给定

id | name      | phone          | account   
  1     null     '339-33-27'       4       
  null   'John'  '339-33-27'       4                    

我想以

结束
id | name       | phone           | account |
  1     'John'    '339-33-27'        4      

但是,我不知道表格中遗漏了哪些值。 解决这类问题的一般方法是什么?我是否只需要使用连接或可能是递归函数?

更新:提供更清晰的示例

id to account is many-to-many 
account to name is many-to-many 
phone to name is one-to-one

数据库基本上是原始事务数据 我想要的是获得我已经/可以找到帐户的所有行

1 个答案:

答案 0 :(得分:0)

如果我理解正确,那么这可能会有效。你需要的是一个自我加入

select t2.id, t1.name, t1.phone, t1.account
from table1 t1
join table1 t2 on t1.account = t2.account and t1.phone = t2.phone
where t1.name is not null

但是,此特定查询依赖于示例数据的假设。我的假设是,如果name不为null,则Id将为null,并且可以通过查看电话号码和帐户找到Id。如果这种假设不正确,那么我们可能需要更多样本数据来解决您的问题。

根据数据的不同,您可能需要左连接或交换,以便T1获取id而不是名称,where条件是ID不为null。用如此小的数据样本量很难说清楚。