如何编写将返回输入的所有数据关系的复杂sql或post sql查询?

如何编写将返回输入的所有数据关系的复杂sql或post sql查询?,sql,oracle,Sql,Oracle,例如,一个帐户(A1)有两个拥有该帐户的客户(C1、C2)。C1也是另一个客户(C3)的单独账户(A2)的所有者。C2也是另外两个账户(A3、A4)的所有者,另一个客户(C4)是A4的共同所有者 我正在寻找一个(循环?)查询,该查询将识别数据输入A1的所有关系(例如A2-4、C1-4) | Account | Customer | |---------|----------| | A1 | C1 | | A1 | C2 | | A2 | C1

例如,一个帐户(A1)有两个拥有该帐户的客户(C1、C2)。C1也是另一个客户(C3)的单独账户(A2)的所有者。C2也是另外两个账户(A3、A4)的所有者,另一个客户(C4)是A4的共同所有者

我正在寻找一个(循环?)查询,该查询将识别数据输入A1的所有关系(例如A2-4、C1-4)

| Account | Customer |
|---------|----------|
| A1      | C1       |
| A1      | C2       |
| A2      | C1       |
| A2      | C3       |
| A3      | C2       |
| A4      | C2       |
| A4      | C4       |
| A5      | C5       |
| A6      | C6       |
尝试: 选择客户,从帐户中选择帐户。客户 其中account=A1; 每个(账户) [查找属于该帐户的所有客户 对于每个(该账户内的客户) [查找属于该客户的所有帐户] ] 当没有新客户或帐户时中断

预期产量

| Account | Customer |
|---------|----------|
| A1      | C1       |
| A1      | C2       |
| A2      | C1       |
| A2      | C3       |
| A3      | C2       |
| A4      | C2       |
| A4      | C4       |

您可以通过分层查询(
connectby
query)实现这一点。因为您正在遍历一个二部图,所以必须小心不要多次生成某些行;我在CONNECT BY子句中这样做,根据级别的奇偶性选择一个条件或另一个条件

如果需要,您可以将起始帐户标识符(在下面的
START WITH
子句中硬编码为“A1”)设置为绑定变量

with
     inputs ( account, customer ) as (
       select 'A1', 'C1' from dual union all       
       select 'A1', 'C2' from dual union all       
       select 'A2', 'C1' from dual union all
       select 'A2', 'C3' from dual union all
       select 'A3', 'C2' from dual union all
       select 'A4', 'C2' from dual union all
       select 'A4', 'C4' from dual union all
       select 'A5', 'C5' from dual union all
       select 'A6', 'C6' from dual
     )
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins BELOW THIS LINE. Use your actual table and column names.
select account, customer
from   inputs
connect by nocycle 
  mod(level, 2) = 1 and account  = prior account
  or
  mod(level, 2) = 0 and customer = prior customer
start with account = 'A1'     -- Or make it a bind variable, if needed
order by account, customer    -- If needed
;

ACCOUNT  CUSTOMER
-------- --------
A1       C1      
A1       C2      
A2       C1      
A2       C3      
A3       C2      
A4       C2      
A4       C4

请阅读此内容并相应地编辑您的问题:请共享您想要关联的每个表的信息,更重要的是,共享生成错误的代码,并避免提出一般性问题。对于格式和模糊性,我们深表歉意。仍在研究如何浏览此网站并提出此类问题。将提供任何必要的更正。谢谢。所以这个查询确实提取了我需要的数据,但是行确实重复了。但是,当我将select语句修改为“select distinct account,customer”时,只返回account+customer的distinct值。@LikestoLearn-Hmm。。。“独特”正是我希望避免的,因为它可能会影响性能。但是如果从(A1,C1)到(A4,C2)有不止一种方法,那么(A4,C2)无论如何都会出现不止一次。如果使用“distinct”给出了正确的答案,并且不会花费太长时间,那么一切看起来都正常。这一点很好。我没有将绩效结果纳入该回应中。是的,不幸的是,从(A1,C1)到(A4,C2)有不止一种方法(可能在我有限的数据集中没有展示)。您是否有一个可以在不影响性能的情况下提供“独特”结果的建议?