这个查询使我的大脑开始受伤,我希望能得到一些指导。该查询的结果是我要获取的三个值: attendanceScore , lootScore 和 totalScore (attendanceScore-lootScore)。 / p>
在三个表中跟踪出勤情况:attendance
,attendancelog
和attendancevalues
。
attendance
记录个人的出勤状态并附加到attendancelog
记录中。出席的类型有“出席”,“错过”和“被叫出”。attendancelog
是父记录,其中记录事件类型,标题和日期以及记录出席者和时间的人。attendancevalues
是一个配置表,它与type
中的出勤率attendance
和type
中的事件attendancelog
相匹配,并返回可配置的value
浮动。在两个表中跟踪赃物: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
有人可以帮助我了解使用什么方法将其清理为更简化和更有效的方法吗?
答案 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