Oracle中父表和子表之间的访问路径

时间:2017-08-28 19:50:25

标签: sql oracle

我有父子表,如下所示。

Child_table | Reference_colums | Parent_table | Referenced_columns
------------|------------------|--------------|-------------------
T1          | Clan_Id          | T0           | Clan_Id
X1          | Clan_Id          | T0           | Clan_Id
X2          | Clan_Id          | T0           | Clan_Id
T2          | Clan_Id          | T1           | Clan_Id
Y1          | Clan_Id          | T1           | Clan_Id
Y2          | Clan_Id          | X1           | Clan_Id
T3          | C31              | T2           | C2
T4          | C4               | T3           | C32

如果我输入(父表= T0,子表为T4) 我应该输出

Child_table | Reference_colums | Parent_table | Referenced_columns
------------|------------------|--------------|-------------------
T1          | Clan_Id          | T0           | Clan_Id
T2          | Clan_Id          | T1           | Clan_Id
T3          | C31              | T2           | C2
T4          | C4               | T3           | C32

因为T4和T0之间的访问路径是 T0-> T1-> T2-> T3-> T4

请帮我在Oracle中编写SELECT查询

2 个答案:

答案 0 :(得分:0)

如@DavidAldrige所述,您需要使用处理分层查询的Oracle CONNECT BY

SELECT * 
FROM tab 
START WITH child = 'T4' 
CONNECT BY prior parent = child and child != 'T0'; 

sqlfiddle demo

答案 1 :(得分:0)

使用Oracle的 connect by 子句绝对没有错。我一直在尝试使用Common Table Expressions(CTE),因为它们不是Oracle专有的。技能转换为其他数据库,在我的例子中是SQL服务器。以下查询将为您提供所需的结果,但使用CTE代替 connect by

DATASET 子句只是设置示例数据, FINDSET 是执行工作的地方:

public class ObjectsSaveController : ApiController
{

    [System.Web.Http.HttpPost]
    public HttpResponseMessage POST([FromBody] int ID, int Year, 
    int typeID, string ObjectList) {


Request URL:myURL/api/ObjectsSave
Request Method:POST
Status Code:404 Not Found 
Remote Address:[::1]:8081
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Length:791
Content-Type:application/json; charset=utf-8
Date:Mon, 28 Aug 2017 21:11:09 GMT
Expires:-1
Persistent-Auth:true
Pragma:no-cache
Server:Microsoft-IIS/8.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:210
Content-Type:application/json;charset=UTF-8
Host:localhost:8081
Origin:http://localhost:8081
Pragma:no-cache
Referer:http://localhost:8081/myURL/
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36
 Request Payload
 view source
 {ID: 211313, Year: 2017, typeID: 7,…}
 cropYear
 :
 2017
 ID
 :
 211313
 ObjectList
 :
 "[{"ID":-1,"Name":"","geoJSONShape":"{\"type\":\"Point\",\"coordinates\":
 [-99.35464723335105,41.54277522419835]}"}]"
 typeID
 :
 7
 Name

这给出了以下结果:

PARENT_TABLE CHILD_TABLE T3 T4
T2 T3
T1 T2
T0 T1