具有两个表的分层查询

时间:2015-01-05 01:04:05

标签: sql database oracle function hierarchical-query

我将此表命名为 "AFP"

ID    || NAME || AFP_FUSION_ID
10    || afp1 ||  
20    || afp2 || 
30    || afp3 || 90
40    || afp4 || 30
50    || afp5 || 30
90    || afp6 ||

引用同一个表的 "ID" is a primary key "AFP_FUSION_ID" is a foreign key

此外,我还有一个名为 "Registers" 的表:

Full Name || AFP_DESTINO
JOHN      || 10
PETER     || 20
ELENA     || 10
MARCO     || 90
DANIELA   || 30
FELIPE    || 40

其中

AFP_DESTINO is a foreign key that references to AFP.ID

我必须创建一个具有类似参数的函数(10,20,30,40,50或90),并且必须返回相应的信息。

  • 如果函数收到'10',则函数必须返回数据from "REGISTERS" where AFP_DESTINO = 10
  • 如果函数收到'30',则必须返回数据where AFP_DESTINO = 30, 40 or 50
  • 如果函数收到'90',则必须返回数据where AFP_DESTINO = 90, 30, 40, 50

我必须使用Oracle,我有这个:

select * from (select * from registers
full outer join afp
on registers.AFP_DESTINO = afp.ID) where afp_destino = 30 or afp_fusion_id = 30

(我必须改进它并稍后转换为函数)。问题是如果我用'30'代替'90',那么当 afp_destino = 40 or 50 时我就没有数据。

有人可以帮帮我吗?

更新:

我有这个代码来解决这个问题:

select * from (select * from registers
full outer join afp
on registers.AFP_DESTINO = afp.ID)  connect by prior
afp_destino = afp_fusion_id start with afp_destino = 90

但会产生不一致,会显示更多行。

1 个答案:

答案 0 :(得分:0)

/*Assuming you have hierarchical data upto three levels
Hope this query may help you only if i got your problem correctly*/
CREATE TABLE AFP
(
ID integer,
Name varchar2(4),
AFP_FUSION_ID number(3,0)
);
INSERT INTO AFP VALUES(10,'afp1',NULL);
INSERT INTO AFP VALUES(20,'afp2',NULL);
INSERT INTO AFP VALUES(30,'afp3',90);
INSERT INTO AFP VALUES(40,'afp4',30);
INSERT INTO AFP VALUES(50,'afp5',30);
INSERT INTO AFP VALUES(90,'afp6',NULL);
CREATE TABLE Registers
(
Full_Name varchar2(10),
AFP_DESTINO number(3,0)
);
INSERT INTO Registers VALUES('Name1',10);
INSERT INTO Registers VALUES('Name2',20);
INSERT INTO Registers VALUES('Name3',10);
INSERT INTO Registers VALUES('Name4',90);
INSERT INTO Registers VALUES('Name5',30);
INSERT INTO Registers VALUES('Name6',40);
WITH AFP_TEST
AS
(Select AFP_1_2.ID_1    as ID_1,
        AFP_1_2.ID_2    as ID_2,
        AFP_3.ID        as ID_3,
        AFP_FUSION_ID_1 as AFP_FUSION_ID_1
from  (select   AFP_1.ID as ID_1,
                AFP_2.ID as ID_2,
                AFP_1.AFP_FUSION_ID as AFP_FUSION_ID_1
                from AFP AFP_1 left outer join AFP AFP_2
        ON AFP_1.ID = AFP_2.AFP_FUSION_ID) AFP_1_2 left outer join AFP AFP_3
        ON AFP_1_2.ID_2 = AFP_3.AFP_FUSION_ID
)
select *
from registers full outer join AFP_TEST afp 
                on registers.AFP_DESTINO = afp.ID_1
where afp_destino = 30 or afp_fusion_id_1 = 90
/*Output : http://sqlfiddle.com/#!4/4291c/3 */