这个问题让我的大脑开始受伤,我希望得到一些指导。我试图获得的查询结果是三个值:attendanceScore、lootScore 和 totalScore (attendanceScore - lootScore)。
通过三个表跟踪出勤情况:
attendance
,attendancelog
,和attendancevalues
.-
attendance
记录个人的出勤状态附加到attendancelog
记录。出席有“出席”、“缺席”和“请出”等类型。 -
attendancelog
是父记录,记录事件类型、标题和日期以及记录出席者和时间。 -
attendancevalues
是一个与出勤type
匹配的配置表来自attendance
和事件type
来自attendancelog
并返回一个可配置的value
float 。
-
战利品通过两个表进行跟踪:
loot
和loottypes
.-
loot
记录每个单独的项目、谁收到的、何时收到的以及内容type
这是战利品(主要、次要、混战)。 -
loottypes
是一个配置表,采用type
来自loot
并返回一个可配置的cost
float 。
-
经过一些工作,我想出了一个有效的查询来获取 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
有人可以帮助我了解使用什么方法将其清理为更精简和高效的东西吗?
最佳答案
您可以使用内联 View
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
关于mysql - 将子查询的 SUM() 结果计算为总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54079588/