一般来说,我是MySQL和SQL的新手,我能够使查询的一部分按预期工作,但是我不确定也不确定如何将查询准确地转换为实现我的目标的子查询。
有关数据库的上下文: 我正在为我的大学会议设计一个应用程序,他们希望法官们能够为演示者拥有的海报评分,演示者可以有多个海报。有五个表。
Judge
Poster
Presenter
Owns
Scores
有关查询的上下文: 下面的查询从得分表中输出演示者的姓名和该特定记录的值的总和
SELECT
presenter.presenter_name,
(visual + clarity + thoroughness
+ breadth + depth + quality
+ discussion + understanding + overall)
AS rec_tot
FROM scores
INNER JOIN judge ON judge.judge_id = scores.judge_ID
INNER JOIN poster ON poster.poster_ID = scores.poster_ID
INNER JOIN owns ON poster.poster_ID = owns.poster_ID
INNER JOIN presenter ON presenter.presenter_ID = owns.presenter_ID
ORDER BY presenter.academic_level, presenter.area_of_study,
presenter.category;
将输出以下内容:
presenter_name | rec_tot
------------------------
nameOne | 17
nameTwo | 27
nameTwo | 18
nameTwo | 16
nameThree | 9
我要执行此查询并按presenter_name输出SUM(rec_tot)组,如下所示:
presenter_name | rec_tot
------------------------
nameOne | 17
nameTwo | 61
nameThree | 9
以下是我试图解决的问题:
SELECT a.*, SUM(rec_tot) AS total
FROM (SELECT (visual + clarity + thoroughness + breadth
+ depth + quality + discussion
+ understanding + overall) AS rec_tot
FROM scores
INNER JOIN judge ON judge.judge_id = scores.judge_ID
INNER JOIN poster ON poster.poster_ID = scores.poster_ID
INNER JOIN owns ON poster.poster_ID = owns.poster_ID
INNER JOIN presenter ON presenter.presenter_ID =
owns.presenter_ID
ORDER BY presenter.academic_level, presenter.area_of_study,
presenter.category
) AS a;
但是,这只是给我所有条目的总和:
rec_tot | total
----------------
27 | 87
但是,每次我尝试使用GROUP BY presenter.presenter_name引用子查询中的表时,都会收到“错误:1054。“ GROUP BY”中的未知列“ presenter.presenter_ID””。因此,我认为父查询无法访问子查询,这导致我尝试在父查询上尝试一起使用子查询中的FROM子句,但是总输出为435,即5x87 ...因此令人困惑。
另外,删除别名“ a”,我得到错误消息“错误:1284。每个派生表必须具有自己的别名”
简而言之,我对别名,子查询的范围以及如何正确实现它们感到非常困惑。
答案 0 :(得分:0)
您几乎了解了这一点,只需按以下方式添加群组:
select a.presenter_name,sum(a.rec_tot)
from
(SELECT
presenter.presenter_name as presenter_name,
(visual + clarity + thoroughness
+ breadth + depth + quality
+ discussion + understanding + overall)
AS rec_tot
FROM scores
INNER JOIN judge ON judge.judge_id = scores.judge_ID
INNER JOIN poster ON poster.poster_ID = scores.poster_ID
INNER JOIN owns ON poster.poster_ID = owns.poster_ID
INNER JOIN presenter ON presenter.presenter_ID = owns.presenter_ID
ORDER BY presenter.academic_level, presenter.area_of_study,
presenter.category) a
group by a.presenter_name