如何只获取一次数据并在联合查询中使用它

时间:2014-07-07 11:34:36

标签: sql db2 union

我的查询以获取有关其朋友或父母的人和信息:

select civils.name, friends.fullName as full_name, friends.age as age, friends.height as height 
from (query to get list people in city) as civils
inner join friends on civils.friendId = friends.Id and friends.name = "John"
union
select civils.name, parents.fullName as full_name, parents.age as age, parents.height as height 
from (query to get list people in city) as civils
inner join parents on civils.parentId = parents.Id and parents.name = "John"

但我不想浪费资源两次获得公民。如何一次获取列表数据并将其用于两个内连接:

select civils.name, full_name, age, height from (query to get list people in city) as civils
inner join friends on civils.friendId = friends.Id and friends.name = "John"
union
inner join parents on civils.parentId = parents.Id and parents.name = "John"

我正在使用DB2。

更新 很抱歉问题不明确,我希望结果如下:

civils.name | full_name | age | height

但如果我尝试了建议答案之类的解决方案,结果格式为:

civils.name | friends.full_name | friends.age | friends.height | parents.full_name | parents.age | parents.height

我还需要再做一步,将此列表转换为我预期的格式列表。

1 个答案:

答案 0 :(得分:1)

我有点担心你在civils引用中做了什么,但是你可以把它包装成CTE:

WITH Civil_List AS (<query to get list people in city>) 

SELECT Civils.name, Friends.full_name, Friends.age, Friends.height
FROM Civils_List
JOIN Friends 
  ON Friends.id  = Civils_List.friendId
     AND Friends.name = 'John' 
UNION 
SELECT Civils.name, Parents.full_name, Parents.age, Parents.height
FROM Civils_List
JOIN Parents 
  ON Parents.id  = Civils_List.friendId
     AND Parents.name = 'John'