SUM Union全部作为select语句的子查询

时间:2018-03-20 17:42:27

标签: mysql

我有三个表:quizcommentquestion。 所有这些都有一个名为activity的{​​{1}}的外键。

我希望activityID单个查询中每个表上的条目数量,并针对相应的sum返回所有活动。

这是我的尝试:

sum

它不起作用,因为在嵌套子查询中找不到SELECT `activity`.`id` AS `activityID`, `activity`.`name`, (SELECT SUM(`count`) FROM ( SELECT COUNT(*) AS `count` FROM `quiz` WHERE `quiz`.`activityID` = `activity`.`id` UNION ALL SELECT COUNT(*) AS `count` FROM `comment` WHERE `comment`.`activityID` = `activity`.`id` UNION ALL SELECT COUNT(*) AS `count` FROM `question` WHERE `question`.`activityID` = `activity`.`id` ) `union`) AS `interactions` FROM `activity` WHERE 1 AND `activity`.`eventID` = 1234 GROUP BY `activity`.`id` ORDER BY `interactions` DESC activity。是否可以将此值添加到嵌套的子查询范围?或者甚至更好,是否有更简单的方法可以在不运行三个单独的子查询并添加它们的情况下执行此操作?

这是我迄今为止最好的解决方案(不使用id):

UNION

感谢。

1 个答案:

答案 0 :(得分:0)

您可以加入所有表格并获取计数。

SELECT
    `activity`.`id` AS `activityID`,
    `activity`.`name`,
    SUM(I.count) as interactions
FROM
    `activity` A INNER JOIN 
    (SELECT `quiz`.`activityID`, COUNT(*) AS `count`
        FROM `quiz` 
        GROUP BY `quiz`.`activityID`
        UNION ALL
        SELECT `comment`.`activityID`, COUNT(*) AS `count`
        FROM `comment`
        GROUP BY `comment`.`activityID`
        UNION ALL
        SELECT `question`.`activityID`, COUNT(*) AS `count`
        FROM `question`
        GROUP BY `question`.`activityID`
    ) interactioncounts I on A.id = I.activityID
WHERE 1
    AND `activity`.`eventID` = 1234
GROUP BY `activity`.`id`
ORDER BY `interactions` DESC