computing sum()将子查询的结果汇总为

zpgglvta  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(325)

我的大脑开始因为这个问题而受伤,我希望得到一些指导。我试图从这个查询中得到三个值:attendancescore、lootscore和totalscore(attendancescore-lootscore)。
出勤率通过三个表进行跟踪: attendance , attendancelog ,和 attendancevalues . attendance 记录附加到 attendancelog 记录。出席的类型有“出席”、“错过”和“叫出”等。 attendancelog 是父记录,记录事件类型、标题和日期,以及记录出勤的人员和时间。 attendancevalues 是与出勤率匹配的配置表 typeattendance 以及事件 typeattendancelog 并返回一个可配置的 value 浮动。
战利品通过两个表进行跟踪: loot 以及 loottypes . loot 记录每个单独的项目,谁收到它,什么时候和什么 type 战利品(主要,次要,免费)。 loottypes 是一个采用 typeloot 并返回一个可配置的 cost 浮动。
经过一段时间的工作之后,我提出了一个工作查询 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

我知道这不管用,但我想补充一点 (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

有没有人能帮我弄明白用什么方法把这些东西清理成更精简、更高效的东西?

olqngx59

olqngx591#

可以使用内联视图

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

相关问题