我正在尝试从表中获取记录。 我的表结构如下,“ id”是主键
| id | location| parent_id |
|----|---------|-----------|
| 1 | abc | NULL |
| 2 | xyz | 1 |
| 3 | def | 2 |
我正在尝试获取ID,名称,parent_id和parent_name。 我正在使用下面的联接查询来获取结果,并且工作正常。 我只是想发表意见,是否有更好的方法来获得结果。
我已经使用联接查询来获取结果。
SELECT location1.id as childid,
location1.location as childlocation ,
locationparent.id as parentid,
locationparent.location as parentlocation
FROM location location1
JOIN location locationparent
ON location1.parent_id = locationparent.id
WHERE location1.id =2 ;
答案 0 :(得分:0)
这里是一个示例,说明如何通过分层查询(使用CONNECT BY)实现此目的。我添加了一些示例数据行,以更好地演示这一概念。
SQL> WITH location_tbl (id, location, parent_id) AS (
2 SELECT 1, 'abc', NULL from dual UNION ALL
3 SELECT 2, 'xyz', 1 from dual UNION ALL
4 SELECT 3, 'def', 2 from dual UNION ALL
5 SELECT 4, 'ggg', 2 from dual UNION ALL
6 SELECT 5, 'hhh', 3 from dual UNION ALL
7 SELECT 6, 'iii', 3 from dual
8 )
9 SELECT id, location, parent_id, PRIOR location parent_location
10 FROM location_tbl
11 CONNECT BY PRIOR id = parent_id
12 START WITH id = 1;
ID LOCATION PARENT_ID PARENT_LOCATION
---------- -------- ---------- ---------------
1 abc
2 xyz 1 abc
3 def 2 xyz
5 hhh 3 def
6 iii 3 def
4 ggg 2 xyz