如果记录不存在,则查询备用表

时间:2014-08-07 05:31:49

标签: sql sql-server-2008

我有两个问题,如下所示

SELECT  i.IncidentId, rl.Description Category FROM incident i
JOIN  IncidentLikelihood l ON i.IncidentId = l.IncidentId
JOIN IncidentSeverity s ON i.IncidentId = s.IncidentId
JOIN LikelihoodSeverity ls ON l.LikelihoodId = ls.LikelihoodId AND s.SeverityId = ls.SeverityId
JOIN RiskLevel rl ON ls.RiskLevelId = rl.riskLevelId

并且

SELECT  i.IncidentId, rl.Description Category FROM incident i
JOIN  incidentreportlikelihood l ON i.IncidentId = l.IncidentId
JOIN IncidentReportSeverity s ON i.IncidentId = s.IncidentId
JOIN LikelihoodSeverity ls ON l.LikelihoodId = ls.LikelihoodId AND s.SeverityId = ls.SeverityId
JOIN RiskLevel rl ON ls.RiskLevelId = rl.riskLevelId

我需要使用WITH子句准备一个查询,以便在两个查询运行的子句中,然后可以将该视图与另一个表连接。

你们能告诉我如何继续吗?

我试过UNION,但这对我没用。我正在寻找使用IFEXISTSEXISTS的地方 - 有些人喜欢吼叫:

WITH IncidentCategory AS (

SELECT i.IncidentId, rl.Description Category FROM incident i
JOIN  IncidentLikelihood l ON i.IncidentId = l.IncidentId
JOIN IncidentSeverity s ON i.IncidentId = s.IncidentId
JOIN LikelihoodSeverity ls ON l.LikelihoodId = ls.LikelihoodId AND s.SeverityId = ls.SeverityId
JOIN RiskLevel rl ON ls.RiskLevelId = rl.riskLevelId
WHERE EXISTS (SELECT NULL)
OR
(SELECT  i.IncidentId, rl.Description Category FROM incident i
JOIN  incidentreportlikelihood l ON i.IncidentId = l.IncidentId
JOIN IncidentReportSeverity s ON i.IncidentId = s.IncidentId
JOIN LikelihoodSeverity ls ON l.LikelihoodId = ls.LikelihoodId AND s.SeverityId = ls.SeverityId
JOIN RiskLevel rl ON ls.RiskLevelId = rl.riskLevelId)
)

更多的想法:对于每个行[incidentid],如果第一个查询返回任何结果 - 它应该显示否则第二个查询结果应该显示

1 个答案:

答案 0 :(得分:1)

如果我正确理解了这些要求,你必须运行第一个查询,如果没有结果,则应该运行第二个查询。

实际上你可以将这两个查询联合起来。第二个中的行数应取决于第一个。如果第一个的count(*)返回> 0,则包括第二个查询行。参见示例

SELECT  i.IncidentId, rl.Description Category FROM incident i
JOIN  IncidentLikelihood l ON i.IncidentId = l.IncidentId
JOIN IncidentSeverity s ON i.IncidentId = s.IncidentId
JOIN LikelihoodSeverity ls ON l.LikelihoodId = ls.LikelihoodId AND s.SeverityId = ls.SeverityId
JOIN RiskLevel rl ON ls.RiskLevelId = rl.riskLevelId

UNION

SELECT  i.IncidentId, rl.Description Category FROM incident i
JOIN  incidentreportlikelihood l ON i.IncidentId = l.IncidentId
JOIN IncidentReportSeverity s ON i.IncidentId = s.IncidentId
JOIN LikelihoodSeverity ls ON l.LikelihoodId = ls.LikelihoodId AND s.SeverityId = ls.SeverityId
JOIN RiskLevel rl ON ls.RiskLevelId = rl.riskLevelId
join (select count(*) as count 
      FROM incident i
      JOIN  IncidentLikelihood l ON i.IncidentId = l.IncidentId
      JOIN IncidentSeverity s ON i.IncidentId = s.IncidentId
      JOIN LikelihoodSeverity ls ON l.LikelihoodId = ls.LikelihoodId AND s.SeverityId =       ls.SeverityId
      JOIN RiskLevel rl ON ls.RiskLevelId = rl.riskLevelId) q1_copy on q1_copy.count=0