从两个表中对SQL中的列进行求和

时间:2012-04-16 23:42:18

标签: php mysql sql sum

我正在使用MySQL并尝试将用户参与活动的小时数相加,但仅限于特定组织。

编辑:我有另一个表混入(misEvents)。我认为GROUP BY语句引起了一些问题,但我不太清楚如何处理它。

table events: contains the "event" information. orgID is the ID of the organization hosting it
-each listing is a separate event

ID | orgID | hours
1  |   1   |   1
2  |   1   |   2
3  |   2   |   1

table eventUserInfo: shows which users attended the events
-refID references the ID column from the events table

ID | refID | userID
 1 |   1   |   1
 2 |   1   |   3
 3 |   2   |   2
 4 |   2   |   1 
 5 |   3   |   2

table miscEvents
-these are entered in manually if an event by an organization wasn't posted on the site, but
the users still wants to keep track of the hours

ID |  userID  | orgID |  Hours
1  |    1     |  1    |    2

因此,当我查看组织1的成员活动时,应显示以下表格

userid | total hours
  1    |      5      //participated in ID #1 and 2 and a misc event, total of 4 hours
  2    |      2      //participated in ID #2 only for org 1
  3    |      1      //participated only in ID #1

假设给定的输入是$ orgID,在这种情况下设置为1

SELECT eventUserInfo.userID, sum(events.hours) as hours,sum(miscEvents.hours) AS mhours FROM events 
JOIN eventUserInfo ON events.ID = eventUserInfo.refID 
JOIN miscEvents ON events.orgID = miscEvents.orgID
WHERE events.orgID = '$orgID'
GROUP BY eventUserInfo.userID

3 个答案:

答案 0 :(得分:2)

我认为应该是:

SELECT eventInfo.userID               --- there is no "events.userID" column
     , SUM(events.hours) AS hours     --- alias added
FROM events 
  JOIN eventInfo                      --- no need for LEFT JOIN
    ON events.ID = eventInfo.refID    
WHERE events.orgID = '$orgID'
GROUP BY eventInfo.userID

问题可能在于您尝试使用"hours"打印$event['hours'],但未返回hours列(仅userID和{{1}如上所述,在SUM(event.hours)列表中使用别名。

答案 1 :(得分:2)

或者因为eventINFO似乎是查询中的主要表:

SELECT eventINFO.userID, SUM(events.hours)
FROM eventINFO
JOIN events ON eventINFO.refID = events.ID
WHERE events.orgID = '$orgID'
GROUP BY eventINFO.userID

应该和ypercube一样,但对我来说,在FROM调用

中调用主表似乎更清楚一点

答案 2 :(得分:1)

对于你的新问题,你需要摆脱这个:

sum(events.hours + miscEvents.hours)

如果我没有弄错的话,您在SUM中不能有多列,每次调用只能添加一列。

我会尝试类似的事情:

SUM(events.hours) AS hours, SUM(miscEvents.hours) AS mhours

然后,在您的函数中,将这些值$total = hours + mhours

加在一起