试试这个:
SELECT
eventMatch.userID,
SUM(eventMatch.eventTypeID = 1) As TypeOne,
SUM(eventMatch.eventTypeID = 2) As TypeTwo,
COUNT( * )
FROM `eventMatch`
INNER JOIN activity ON eventMatch.activityID = activity.activityID
INNER JOIN activityMatch ON activity.activityID = activityMatch.activityID
WHERE activity.khID =1
GROUP BY userID
ORDER BY userID ASC;
更新 1
对于多种事件类型,您可以像这样动态地执行此操作:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT CONCAT('SUM(IF(em.eventTypeID = ''',
em.eventTypeID, ''', 1, 0)) AS Type',
em.eventTypeID )
) INTO @sql
FROM `eventMatch` AS em;
SET @sql = CONCAT('SELECT em.userID, ', @sql,
', COUNT( * )
FROM `eventMatch` AS em
INNER JOIN activity AS a ON em.activityID = a.activityID
INNER JOIN activityMatch AS am ON a.activityID = am.activityID
GROUP BY em.userID
ORDER BY em.userID ASC ;');
prepare stmt
FROM @sql;
execute stmt;
更新 2
如果您想从EventTypes
表中排除所有类型,即使此类型在其他表中没有匹配项,您也应该在第一步中从该表中动态获取类型列表,EventTypes
而不是从表中获取它们eventmatch
然后执行动态查询方式与之前相同。像这样:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT CONCAT('SUM(IF(em.eventTypeID = ''',
em.eventTypeID, ''', 1, 0)) AS Type',
em.eventTypeID )
) INTO @sql
FROM eventTypes AS em; -- <---------- this is what I changed.
SET @sql = CONCAT('SELECT em.userID, ', @sql,
', COUNT( * )
FROM `eventMatch` AS em
INNER JOIN activity AS a ON em.activityID = a.activityID
INNER JOIN activityMatch AS am ON a.activityID = am.activityID
GROUP BY em.userID
ORDER BY em.userID ASC ;');
prepare stmt
FROM @sql;
execute stmt;