我需要使用连接查询来获取同一个表中可用的行值。
示例:
Id (Primary Key) Name Address Parent Organization ID (Foreign Key) reference (Id)
1 Sup Org1 Address1 null
2 Sup Org2 Address2 null
3 Sup Org3 Address3 null
4 Sub Org5 Address4 1
输出:
Name Address
Sup Org1 Address1
Sup Org2 Address2
Sup Org3 Address3
Sub Org5(Sup Org1) Address4
除超级组织价值外,所有子组织都应附加 映射的超级组织(例如:Sub Org5(Org1))。
任何人都可以帮我解决此问题,以便像上面的输出格式一样编写查询
答案 0 :(得分:0)
我没有测试,但这应该涵盖
Select
t1.Name || Decode(NVL(t2.Name , ''), '', '', '(' || t2.Name || ')'), -- here we convert null to empty string and don't wrap empty string into parenthesis
Address
From Mytable t1 left join
Mytable t2 on t1.id = t2.Parent
答案 1 :(得分:0)
这里是SQL Fiddle(下次有这样的问题时你应该提供),这里是SQL:
SELECT o2.Name, case when o1.Name is not null then '(' || o1.Name || ')' END, o2.Parent_Organization_ID, 01.Address
FROM Organization o1
RIGHT JOIN Organization o2 on o1.id = o2.Parent_Organization_ID
ORDER BY o2.NAME
答案 2 :(得分:-1)
您正在寻找的程序称为"自我加入"。 sql zoo有一些可能有助于提高技能的课程。
没有提供小提琴,但这看起来对我来说是正确的:
select sub.name||coalesce('('||sup.name||')',''),address
from table_name as sub
left join table_name as sup on sub.parent=sup.id