计算子查询的SUM()结果总计

时间:2019-01-07 18:10:45

标签: mysql sql

这个查询使我的大脑开始受伤,我希望能得到一些指导。该查询的结果是我要获取的三个值: attendanceScore lootScore totalScore (attendanceScore-lootScore)。 / p>

  • 在三个表中跟踪出勤情况:attendanceattendancelogattendancevalues

    • attendance记录个人的出勤状态并附加到attendancelog记录中。出席的类型有“出席”,“错过”和“被叫出”。
    • attendancelog是父记录,其中记录事件类型,标题和日期以及记录出席者和时间的人。
    • attendancevalues是一个配置表,它与type中的出勤率attendancetype中的事件attendancelog相匹配,并返回可配置的value浮动。
  • 在两个表中跟踪赃物:lootloottypes

    • loot记录每个单独的物品,接收它的物品以及物品的type掠夺时间和物品(主要,次要,免费)。
    • loottypes是一个配置表,它从type中提取loot,并返回可配置的cost FLOAT。

经过一些工作,我想出了一个有效的查询来获取attendanceScorelootScore

SELECT 
(SELECT SUM(t3.`value`)
FROM `attendance` t1
    INNER JOIN `attendancelog` t2
        ON t2.`id` = t1.`attendancelog_id`
    INNER JOIN `attendancevalues` t3
        ON t3.`eventtype_id` = t2.`type` AND t3.`attendancetype_id` = t1.`type`
WHERE t1.`user_id` = 3) as attendanceScore,

(SELECT SUM(t2.`cost`) 
    FROM `loot` t1
        INNER JOIN `loottypes` t2
            ON t2.`id` = t1.`type`
    WHERE t1.`user_id` = 3) as lootScore

我知道这行不通,但是我尝试向查询中添加(attendanceScore - lootScore),但是它说这些字段不可用。最终,这就是我需要完成的查询。

可以通过将每个子查询直接复制到(attendanceScore - lootScore)中来获得所需的结果,但这绝对是令人毛骨悚然的,我相信这是不必要的:

SELECT 
(SELECT SUM(t3.`value`)
FROM `attendance` t1
    INNER JOIN `attendancelog` t2
        ON t2.`id` = t1.`attendancelog_id`
    INNER JOIN `attendancevalues` t3
        ON t3.`eventtype_id` = t2.`type` AND t3.`attendancetype_id` = t1.`type`
WHERE t1.`user_id` = 3) as attendanceScore,

(SELECT SUM(t2.`cost`) 
    FROM `loot` t1
        INNER JOIN `loottypes` t2
            ON t2.`id` = t1.`type`
    WHERE t1.`user_id` = 3) as lootScore,

(
    (SELECT SUM(t3.`value`)
    FROM `attendance` t1
        INNER JOIN `attendancelog` t2
            ON t2.`id` = t1.`attendancelog_id`
        INNER JOIN `attendancevalues` t3
            ON t3.`eventtype_id` = t2.`type` AND t3.`attendancetype_id` = t1.`type`
    WHERE t1.`user_id` = 3) - (SELECT SUM(t2.`cost`) 
    FROM `loot` t1
        INNER JOIN `loottypes` t2
            ON t2.`id` = t1.`type`
    WHERE t1.`user_id` = 3)
) as totalScore

有人可以帮助我了解使用什么方法将其清理为更简化和更有效的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用嵌入式视图

SELECT attendanceScore,
        lootScore,
        attendanceScore - lootScore as totalScore
FROM
(
    SELECT 
    (
        SELECT SUM(t3.`value`)
        FROM `attendance` t1
        INNER JOIN `attendancelog` t2
            ON t2.`id` = t1.`attendancelog_id`
        INNER JOIN `attendancevalues` t3
            ON t3.`eventtype_id` = t2.`type` AND t3.`attendancetype_id` = t1.`type`
        WHERE t1.`user_id` = 3
    ) as attendanceScore,
    (
        SELECT SUM(t2.`cost`) 
        FROM `loot` t1
        INNER JOIN `loottypes` t2 ON t2.`id` = t1.`type`
        WHERE t1.`user_id` = 3) as lootScore
) t