在结果上循环的SQL查询

时间:2016-01-15 12:07:37

标签: sql sql-server loops common-table-expression recursive-query

我知道这可以做到而且不应该太难,但我的大脑现在什么都不处理。

我有两个表一起工作以执行操作和响应。响应记录本身就是一个动作,所以我有以下内容:

select a.[Action], b.Response, c.Action, d.Response, e.Action,
       f.Response, g.Action, h.Response  
from ValidRecruitmentAction a 
  LEFT OUTER JOIN ValidRecruitmentAction_Response b on a.[key] = b.[actionkey] 

我试图输出所有链接。所以在第一个动作之后我得到了它的响应,但那个动作的响应怎么样?

我最终这样做了:

select a.[Action], b.Response, c.Action, d.Response, e.Action,
       f.Response, g.Action, h.Response 
from ValidRecruitmentAction a
  LEFT OUTER JOIN ValidRecruitmentAction_Response b on a.[key] = b.[actionkey]
  LEFT OUTER JOIN ValidRecruitmentAction c on c.[Key] = b.FollowOnActionKey
  LEFT OUTER JOIN ValidRecruitmentAction_Response d on c.[key] = d.[actionkey]
  LEFT OUTER JOIN ValidRecruitmentAction e on e.[Key] = d.FollowOnActionKey
  LEFT OUTER JOIN ValidRecruitmentAction_Response f on e.[key] = f.[actionkey]
  LEFT OUTER JOIN ValidRecruitmentAction g on g.[Key] = f.FollowOnActionKey
  LEFT OUTER JOIN ValidRecruitmentAction_Response h on g.[key] = h.[actionkey]

我知道有一种更简单的方法可以做到这一点。任何人都可以提醒我如何做到这一点,CTE是必需的。我希望在一个查询中执行此操作,而不是作为过程的一部分。

2 个答案:

答案 0 :(得分:1)

我的大脑今天也不是很强大,但这是我设法得到的。

With CTE as
(
Select a.[key] as Action_key
from ValidRecruitmentAction a
where a.[action = 'My first action'

UNION ALL

Select b.FollowOnActionKey
from ValidRecruitmentAction_Response b
    INNER JOIN CTE ON CTE.Action_key = b.[actionkey]
)

Select  a.[Action], b.Response
from ValidRecruitmentAction a
    INNER JOIN CTE ON CTE.Action_key = a.[key]
    LEFT OUTER JOIN ValidRecruitmentAction_Response b on a.[key] = b.[actionkey]

答案 1 :(得分:0)

它不会表现出色,但您可以加入多个clasues,因此您的ON子句可以是a.[key] = b.[actionkey] OR c.[Key] = b.[actionkey] OR e.[Key] ...,依此类推。

在你的例子/情况中,我宁愿建议你去UNION路线 所以像这样:

   SELECT  a.[Action] ,
            b.Response                
    FROM    ValidRecruitmentAction a
            INNER JOIN ValidRecruitmentAction_Response b ON a.[key] = b.[actionkey]
    UNION
    SELECT  a.[Action] ,               
            c.Response
    FROM    ValidRecruitmentAction a
            INNER JOIN ValidRecruitmentAction b ON a.[Key] = b.FollowOnActionKey

......insert all your remaining cases as unions

然后,您可以为每个案例的每个UNIONS添加WHERE子句;
并且最有可能使他们的表现远远超过您在一次加入中尝试做所有事情时可能最终的表现。