尝试组合多个查询,但无论我尝试将它们连接在一起的哪种方式都会遇到问题。这是两者的模型:
查询 1(获取所有 G 和相关 R):
select distinct
a.g_id,
a.g_name,
b.r_name,
b.r_id
from
g_tab a,
r_tab b,
f_tab c
where
a.g_id = b.g_id
and b.r_id = c.r_id
and c.f_id = 7
order by a.g_id
查询 2(遍历层次结构并过滤到特定组):
with parentGs as
(
select
f.g_id,
f.g_name
from
g_tab f
where
f.delete_indicator is null
connect by
prior f.parent_g_id = f.g_id
start with
f.g_id = 22 --DO NOT WANT THIS HARDCODED
)
select
d.g_name
from
parentGs d,
g_group_members_tab e
where
d.g_id = e.member_g_id
and e.g_group_description = 'test'
我不想更改查询 1 的返回计数,但想加入查询 2 中的 g_name 并将其添加为新的别名列。
这是我试图达到的一个示例,但由于 g_id 在“开始于”中被称为“无效标识符”而不起作用。我知道父值仅在一个子查询深处有效,但如果仅使用一个子查询进行重组(在这种情况下为“来自”),仍然会出现同样的错误:
select distinct
a.g_id,
a.g_name,
b.r_name,
b.r_id,
(select
d.g_name
from
(select
f.g_id,
f.g_name
from
g_tab f
where
f.delete_indicator is null
connect by
prior f.parent_g_id = f.g_id
start with
f.g_id = a.g_id) d, --THIS GIVES INVALID IDENTIFIER
g_group_members_tab e
where
d.g_id = e.member_g_id
and e.g_group_description = 'test') as parent_g_name
from
g_tab a,
r_tab b,
f_tab c
where
a.g_id = b.g_id
and b.r_id = c.r_id
and c.f_id = 7
order by a.g_id
将这两个查询结合在一起的任何帮助将不胜感激。我的目标平台是 Oracle 11g。非常感谢!
* 更新 *
这是一些示例 SQL Fiddle 数据:
create table g_tab
(
g_id number(9),
g_name varchar2(50),
parent_g_id number(9),
delete_indicator char(1)
)
/
create table g_group_members_tab
(
member_g_id number(9),
g_group_description varchar2(50)
)
/
create table r_tab
(
r_id number(9),
r_name varchar2(50),
g_id number(9)
)
/
create table f_tab
(
f_id number(9),
f_name varchar2(50),
r_id number(9)
)
/
insert into g_tab (g_id, g_name, parent_g_id) values (0, 'a', null)
/
insert into g_tab (g_id, g_name, parent_g_id) values (1, 'b', 0)
/
insert into g_tab (g_id, g_name, parent_g_id) values (2, 'c', 1)
/
insert into g_tab (g_id, g_name, parent_g_id) values (3, 'd', null)
/
insert into g_tab (g_id, g_name, parent_g_id) values (4, 'e', 3)
/
insert into g_tab (g_id, g_name, parent_g_id) values (5, 'f', 4)
/
insert into g_tab (g_id, g_name, parent_g_id) values (6, 'g', null)
/
insert into g_group_members_tab (member_g_id, g_group_description) values (1, 'test')
/
insert into g_group_members_tab (member_g_id, g_group_description) values (3, 'test')
/
insert into r_tab (r_id, r_name, g_id) values (0, 'r', 0)
/
insert into r_tab (r_id, r_name, g_id) values (0, 'r', 1)
/
insert into r_tab (r_id, r_name, g_id) values (0, 'r', 2)
/
insert into r_tab (r_id, r_name, g_id) values (0, 'r', 3)
/
insert into r_tab (r_id, r_name, g_id) values (0, 'r', 4)
/
insert into r_tab (r_id, r_name, g_id) values (1, 'rr', 5)
/
insert into r_tab (r_id, r_name, g_id) values (0, 'r', 6)
/
insert into f_tab (f_id, f_name, r_id) values (7, 'f', 0)
/
insert into f_tab (f_id, f_name, r_id) values (7, 'f', 1)
期望的结果:
g_id g_name r_name r_id parent_g_name
0 a r 0 null
1 b r 0 b
2 c r 0 b
3 d r 0 d
4 e r 0 d
5 f rr 1 d
6 g r 0 null