CONNECT BY与递归查询

时间:2019-07-16 13:07:02

标签: oracle plsql

这是我的桌子

CREATE TABLE "FILES" 
   (    
     "DISKELEMENTID" NUMBER NOT NULL ENABLE, 
      "FILENAME" VARCHAR2(200 BYTE), 
      "PARENTDISKELEMENTID" NUMBER, 
       CONSTRAINT "FILES_PK" PRIMARY KEY ("DISKELEMENTID")
   )

和数据:

Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (1,'C:',null);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (2,'D:',null);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (3,'C:\OperatingSystem',1);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (4,'C:\Temp',1);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (5,'D:\Video',2);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (6,'D:\Music',2);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (7,'C:\OperatingSystem\file01.txt',3);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (8,'C:\OperatingSystem\file02.txt',3);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (9,'D:\Video\video01.avi',5);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (10,'D:\Video\video01.avi',5);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (11,'D:\Video\Temp',5);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (12,'D:\Video\Temp\file-d-temp01.txt',11);
Insert into FILES (DISKELEMENTID,FILENAME,PARENTDISKELEMENTID) values (13,'D:\Video\Temp\file-d-temp02.txt',11);

我想解释一下/仔细检查我的代码是否相同:使用CONNECT by实现的相同查询和使用递归查询实现的相同查询。 即使返回的数据相同,我也想检查/解释为什么相同。

使用CONNECT BY查询:

SELECT Files.DiskElementId,
   prior FileName as Parent,
  CONNECT_BY_ROOT FileName as TopParent,
  Files.FileName FROM Files 
  START WITH ParentDiskElementID is NULL
  connect by prior DiskElementID = ParentDiskElementID 
  ORDER BY DiskElementId

并使用递归查询进行查询:

with q(DiskElementId, Parent,TopParent,FileName) as
(
  SELECT 
      DiskElementId, 
      null as Parent, 
      FileName as TopParent,
      FileName
    FROM Files WHERE parentdiskelementid is null
  UNION ALL
  SELECT
      Files.DiskElementId,
      q.FileName /* prior filename ?? */ as Parent,
      q.TopParent /*CONNECT_BY_ROOT FileName as TopParent ??? */ as TopParent,
      Files.FileName
    FROM Files INNER JOIN q ON files.parentdiskelementid = q.DiskElementId
)
SELECT DiskElementId, Parent,TopParent,FileName FROM q ORDER BY DiskElementId;

两个查询都返回相同的数据

0 个答案:

没有答案