具有嵌套选择的SQL仅在应显示多个时返回一行

时间:2014-07-31 11:31:55

标签: mysql sql join

我有以下sql:

SELECT          
            ROUND(SUM(MS.score) / count(P.module_id),2) AS average_score,
            (SELECT Count(MS.phase_id) FROM Module_score MS WHERE MS.phase_id = P.id) as attempts,
            (SELECT ROUND(Count(MS.phase_id)/ (SELECT COUNT(user_id) FROM User_has_Team WHERE Team_id = 1) *100,2) FROM Module_score MS WHERE phase_id = P.id) as percent_completed
            FROM
              Module_score MS
                 LEFT JOIN
            `Phase` P ON P.module_id = MS.module_id
                JOIN User U on U.id = MS.user_id
            WHERE
             P.academy_id = 1 AND P.team_id = 1 AND P.start < now()

返回以下内容:

# id, average_score, attempts, percent_completed
 '89',   '3.94',         '2',      '100.00'

现在这很好但它应该返回now()

之前的所有阶段

以下是:

阶段表

'89', '1', '1', '1', '2014-07-08 00:00:00', '1', 'none', '22:22', 'none', '1'
'90', '1', '1', '1', '2014-07-22 00:00:00', '2', 'none', 'none', 'none', '1'
'91', '3', '1', '1', '2014-07-08 00:00:00', '3', 'gege', '123451', 'Marc Rasmussen', '0'
'92', '1', '1', '1', '2013-02-15 00:00:00', '4', 'none', 'none', 'none', '1'

我尝试了很多不同的方法,但没有运气

任何人都可以把我推向正确的方向或向我解释为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

这是您的查询:

SELECT ROUND(SUM(MS.score) / count(P.module_id),2) AS average_score,
-------------^ --------------^
       (SELECT Count(MS.phase_id) FROM Module_score MS WHERE MS.phase_id = P.id) as attempts,
       (SELECT ROUND(Count(MS.phase_id)/ (SELECT COUNT(user_id) FROM User_has_Team WHERE Team_id = 1) *100,2) FROM Module_score MS WHERE phase_id = P.id) as percent_completed
FROM Module_score MS LEFT JOIN
     `Phase` P
     ON P.module_id = MS.module_id JOIN
     User U on U.id = MS.user_id
WHERE P.academy_id = 1 AND P.team_id = 1 AND P.start < now();

这些将查询转换为聚合查询。没有group by,这样的查询只返回一行。在大多数SQL版本中,此查询将返回错误,因为您使用p.id关联子查询,但这不是group by子句的一部分。 MySQL允许通过group by扩展。我猜你想要:

SELECT p.id,
       ROUND(SUM(MS.score) / count(P.module_id),2) AS average_score,
       (SELECT Count(MS.phase_id) FROM Module_score MS WHERE MS.phase_id = P.id) as attempts,
       (SELECT ROUND(Count(MS.phase_id)/ (SELECT COUNT(user_id) FROM User_has_Team WHERE Team_id = 1) *100,2) FROM Module_score MS WHERE phase_id = P.id) as percent_completed
FROM Module_score MS LEFT JOIN
     `Phase` P
     ON P.module_id = MS.module_id JOIN
     User U on U.id = MS.user_id
WHERE P.academy_id = 1 AND P.team_id = 1 AND P.start < now()
GROUP BY p.id;

这可能会做你想要的。相关的子查询看起来很复杂,所以我怀疑它们可以简化。但是,目前还不清楚你真正想要的结果。