显示一个表中的所有记录并匹配另一个表中的记录

时间:2013-11-01 15:35:36

标签: mysql sql

您好我有一张下表,其中包含活动和积分记录

Activites
|A_ID   |Site        | ActivityValue| ActivityName
 ---------------------------------------------------
|1      | site1      | 7             | ActivityName1
|2      | site1      | 6             | ActivityName2
|2      | site1      | 6             | ActivityName3
|2      | site1      | 6             | ActivityName4  



pointsTable
|UserID |RemainderPoints  | Active         | ActivityName |
------------------------------------------------------
|1      | 10              | TRUE           | ActivityName1| 
|2      | 5               | TRUE           | ActivityName2| 
|2      | 5               | TRUE           | ActivityName3| 
|2      | 5               | TRUE           | ActivityName3|  

我需要的是返回活动

中的所有记录
SELECT  ActivityName FROM activity WHERE `Site`='Site1' 

返回

ActivityName1
ActivityName2
ActivityName3
ActivityName4    

然后我需要根据来自pointstable

的用户ID对用户点进行求和
SELECT UserID, ActivityName, Active,  SUM( RemainderPoints) 
FROM pointstable
WHERE UserID =2
AND Active =  'TRUE'  GROUP BY ActivityName    

返回

|UserID |RemainderPoints   | Active         | ActivityName |
-------------------------------------------------------------
|2      | 5                | TRUE           | ActivityName2| 
|2      | 10               | TRUE           | ActivityName3|    

所有这些都是单独的,但我需要将它们放在一起供用户使用,即

ActivityName1  = 0
ActivityName2  = 5
ActivityName3  =10
ActivityName4  = 0

任何指针?

2 个答案:

答案 0 :(得分:2)

使用外部联接:

select 
    a.activityName, 
    coalesce(sum(pt.remainderPoints), 0) points
from 
    activities a left outer join pointsTable pt on 
        pt.activityName = a.activityName and pt.UserID = 2
group by a.activityName

或子查询:

select
    activities.ActivityName,
    coalesce(
        (select sum(RemainderPoints) from pointsTable where pointsTable.UserId = 2 and pointsTable.ActivityName = activities.ActivityName)
    , 0) points
from
    activities

答案 1 :(得分:0)

SELECT a.ActivityName,SUM( p.RemainderPoints) FROM activity a left join pointstable p on a.ActivityName =p.ActivityName WHERE p.UserID =2 AND p.Active = 'TRUE' and a.site ='Site1' GROUP BY a.ActivityName

希望这有帮助!