SQL查询与JOIN相乘

时间:2014-05-15 15:50:07

标签: sql

我有一张带有ID#的表格。我想计算其他2个表(一个在另一个数据库中)中的行,并显示每个表与该ID有多少记录。 2个单独的查询可以工作,但是当我将它们组合起来时,结果会成倍增加。 这是我的代码:

The First Count works:
SELECT PRIMARY.dbo.MainTbl.FileIDRef, COUNT(PRIMARY.dbo.1stTbl.FileIDRef) AS 1stCnt
FROM PRIMARY.dbo.MainTbl
INNER JOIN PRIMARY.dbo.1stTbl ON PRIMARY.dbo.MainTbls.FileIDRef = PRIMARY.dbo.1stTbl.FileIDRef
GROUP BY PRIMARY.dbo.MainTbl.FileIDRef, PRIMARY.dbo.1stTbl.FileIDRef

Result
FileIDRef    1stCnt
2011         135

The 2nd count works:
SELECT PRIMARY.dbo.MainTbl.FileIDRef, COUNT(2NDARY.dbo.2ndTbl.FileIDRef) AS 2ndCnt
FROM PRIMARY.dbo.MainTbl
INNER JOIN 2NDARY.dbo.2ndTbl ON DB1.PRIMARY.MainTbls.FileIDRef = 2NDARY.dbo.2ndTbl.FileIDRef
GROUP BY PRIMARY.dbo.MainTbl.FileIDRef, 2NDARY.dbo.2ndTbl.FileIDRef

Result
FileIDRef    2ndCnt
2011         115

The Combined query gives a multiply of 1st and 2nd choice
SELECT PRIMARY.dbo.MainTbl.FileIDRef, COUNT(PRIMARY.dbo.1stTbl.FileIDRef) AS 1stCnt, 
COUNT(2NDARY.dbo.2ndTbl.FileIDRef) AS 2ndCnt
FROM PRIMARY.dbo.MainTbl
INNER JOIN PRIMARY.dbo.1stTbl ON PRIMARY.dbo.MainTbls.FileIDRef = PRIMARY.dbo.1stTbl.FileIDRef
INNER JOIN 2NDARY.dbo.2ndTbl ON DB1.PRIMARY.MainTbls.FileIDRef = 2NDARY.dbo.2ndTbl.FileIDRef
GROUP BY PRIMARY.dbo.MainTbl.FileIDRef, PRIMARY.dbo.1stTbl.FileIDRef, 2NDARY.dbo.2ndTbl.FileIDRef

Result
FileIDRef    1stCnt    2ndCnt
2011         18975     18975

Result Should be:
FileIDRef    1stCnt   2ndCnt
2011         135      115

我错过了什么?

0 个答案:

没有答案