日期:2014-05-18  浏览次数:20494 次

关联二个表的操作.
SELECT A.ID, A.userID, A.PlanName, A.Count, B.clickCount, B.clickMoneyCount
FROM dbo.Plan AS A INNER JOIN
(SELECT SUM(clickCount) AS clickCount, SUM(clickMoneyCount) AS clickMoneyCount, ID
FROM dbo.Click GROUP BY ID) AS B ON A.ID = B.ID


要是这样写的话。。。
数据:: a表中有三条记录...(1,'张三',‘计划1','5')
  ...(2,'张三',‘计划2','6')
  ...(3,'张三',‘计划3','7')

  b表中只有二条记录 (,......,1,20,20)
  (,......,2,20,20)

这样写的话,会把a表中的 属于 '张三'userID ID=3 记录 ...(3,'张三',‘计划3','7') 给漏掉了.

要如何改使的。。A表中 userID='张三' 记录全显示。。再关联B表中的B.clickCount, B.clickMoneyCount,并且是求和的.

------解决方案--------------------
INNER JOIN改成LEFT JOIN,然后带B.的都加ISNULL
------解决方案--------------------
SQL code
isnull

------解决方案--------------------
select a.* , isnull(b.col , 0)
from a left join b on a.id = b.id
------解决方案--------------------
SQL code
SELECT    
  A.ID, A.userID, A.PlanName, A.Count, ISNULL(B.clickCount,0),ISNULL( B.clickMoneyCount,0) 
FROM  
  dbo.Plan AS A 
LEFT JOIN
  (SELECT  SUM(clickCount) AS clickCount, SUM(clickMoneyCount) AS clickMoneyCount, ID 
FROM    
  dbo.Click  GROUP BY ID) AS B ON A.ID = B.ID

------解决方案--------------------
探讨
SQL codeSELECT
A.ID, A.userID, A.PlanName, A.Count,ISNULL(B.clickCount,0),ISNULL( B.clickMoneyCount,0)FROM
dbo.PlanAS ALEFTJOIN
(SELECTSUM(clickCount)AS clickCount,SUM(clickMoneyCount)AS clickMoneyCount, IDFROM
dbo.ClickGROUPBY ID)AS BON A.ID= B.ID