删除具有左连接的另一个选择的查询

时间:2014-12-08 16:09:17

标签: sql sql-server database

我必须删除此选择的结果。 我试图创建一个新表并在其中插入select的结果,然后删除。 谁能帮帮我?

select * 
from SurveySession ss (nolock)
left join
SurveySessionPages sp 
on ss.Id = sp.SurveySessionID
left join 
SurveySessionAnswers sa
on ss.Id = sa.SurveySessionID
left join 
SurveySessionAnswerChoices sac
on sa.Id = sac.SurveySessionAnswerId
left join 
SurveySessionXmlData sxd
on ss.Token = sxd.Token
where ss.StartedOn <= dateadd(day,datediff(day,0,getdate())-365,0) 
and (ss.UpdatedOn is null or ss.UpdatedOn <= dateadd(day,datediff(day,0,getdate())-365,0)))

3 个答案:

答案 0 :(得分:0)

您可以将查询用作子查询并删除其结果。

DELETE FROM SurveySession WHERE Id=(select * 
from SurveySession ss (nolock)
left join
SurveySessionPages sp 
on ss.Id = sp.SurveySessionID
left join 
SurveySessionAnswers sa
on ss.Id = sa.SurveySessionID
left join 
SurveySessionAnswerChoices sac
on sa.Id = sac.SurveySessionAnswerId
left join 
SurveySessionXmlData sxd
on ss.Token = sxd.Token
where ss.StartedOn <= dateadd(day,datediff(day,0,getdate())-365,0) 
and (ss.UpdatedOn is null or ss.UpdatedOn <= dateadd(day,datediff(day,0,getdate())-365,0))))    

答案 1 :(得分:0)

您可以添加delete而不是select,并按照这样做。

delete SurveySession 
from SurveySession ss 
left join
SurveySessionPages sp 
on ss.Id = sp.SurveySessionID
left join 
SurveySessionAnswers sa
on ss.Id = sa.SurveySessionID
left join 
SurveySessionAnswerChoices sac
on sa.Id = sac.SurveySessionAnswerId
left join 
SurveySessionXmlData sxd
on ss.Token = sxd.Token
where ss.StartedOn <= dateadd(day,datediff(day,0,getdate())-365,0) 
and (ss.UpdatedOn is null or ss.UpdatedOn <= dateadd(day,datediff(day,0,getdate())-365,0)))

答案 2 :(得分:0)

你需要回答NoDisplayName的问题才能获得明确的答案,但是:

  1. 如果您只想从SurveySession中删除,只需将其更改为删除并删除所有左连接,因为它们没有对SurveySession进行任何过滤。
  2. 如果你想删除其中一个表,我会将查询重组为surveysession和该表之间的内部联接。
  3. 如果要删除所有符合where条件的surveysession记录以及所有与surveysession匹配的左连接表,则应为每个记录创建一个删除语句(有两种不同的方法)。