SQL连接给出了错误的计数

时间:2014-05-04 12:29:30

标签: sql sql-server sql-server-2008 join

我在下面用非an​​si编写了一个查询,我将转换为ansi,用于从SQL 2008迁移到2012.问题是以下查询的计数不匹配。

 Select  count(*) 
 FROM t1 ,t2 ,t3,t4,t5
 WHERE t3.RequestId = t1.GenRequestId
 AND t1.RequestType = 'xxx'
 AND t4.RequestId =* t3.RequestId
 AND t4.ItemTypeId =* t2.ItemTypeId 
 AND t1.managerid *= t5.managerid 

 Select  count(*)
 FROM t1
 LEFT JOIN t5 ON t1.managerid = t5.managerid,
 t4
 RIGHT JOIN t3 ON t4.RequestId = t3.RequestId
 RIGHT JOIN t2 ON t4.ItemTypeId = t2.ItemTypeId
 WHERE t3.RequestId = t1.GenRequestId
 AND t1.RequestType = 'xxx' 

使用连接时我想要相同的数量。感谢你的帮助.. !!

1 个答案:

答案 0 :(得分:1)

要解决这个问题,请重写原文,以便所有内容都是左外连接:

Select  count(*) 
 FROM t1 ,t2 ,t3,t4,t5
 WHERE t3.RequestId = t1.GenRequestId
 AND t1.RequestType = 'xxx'
 AND t3.RequestId *= t4.RequestId
 AND t2.ItemTypeId *= t4.ItemTypeId 
 AND t1.managerid *= t5.managerid ;

然后使用此建议的顺序进行最终查询(左侧的表格需要出现在右侧的表格之前):

 SELECT  count(*)
 FROM t1 INNER JOIN
      t3
      ON t3.RequestId = t1.GenRequestId LEFT OUTER JOIN
      t4
      ON t3.RequestId = t4.RequestId LEFT OUTER JOIN
      t2
      ON t2.ItemTypeId = t4.ItemTypeId LEFT OUTER JOIN
      t5
      ON t1.managerid = t5.managerId;
 WHERE t1.RequestType = 'xxx';

说实话,我发现旧式连接语法很难处理。并且,我发现使用left outer joinright outer join的混合物非常困难。我倾向于回到数据并从头开始重写查询。