0

我正在使用 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
4

3 回答 3

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

FROM应该导致与 ypercube 相同,但对我来说,在通话中调用您的主表似乎更清楚一些

于 2012-04-16T23:59:54.697 回答
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"with:$event['hours']但没有hours返回列(只有userIDand SUM(event.hours)。在列表中使用别名SELECT,如上所述。

于 2012-04-16T23:50:45.260 回答
1

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

sum(events.hours + miscEvents.hours)

如果我没记错的话,你不能有多个列,SUM每次调用只能添加一个列。

我会尝试类似的东西:

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

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

于 2012-04-18T03:25:38.187 回答