当我使用groupby子句时,列将消失



架构

我需要找到每个学生的学费和学生的名字,当我在查询中使用group-by时,我会得到学生的名字或student_num,但不能同时得到。这是我使用的查询

select e.student_num as StudentID, s.student_name as Name,
sum(c.num_credits*450) as Tuition from students s, enrolls e, sections se, courses c 
where e.student_num = s.student_num 
and e.section_id=se.section_id 
and se.course_num=c.course_num
group by s.student_name;

现在,此表提供了正确的学生id和正确的学费,但没有在姓名栏中显示姓名。如有任何帮助,我们将不胜感激!谢谢我还附上了模式供参考

严格来说,SELECT子句中引用的表达式或列应该。。。

  • 是集合(MIN()MAX()SUM()等(的一部分
  • 在CCD_ 5条款中提及

例如,您希望以下内容返回什么?

INSERT INTO table VALUES (1, 'foo', 10)
INSERT INTO table VALUES (1, 'bar', 20)
SELECT a, b, SUM(c) FROM table GROUP BY a

由于GROUP BY a,您只能返回一个结果行。但你也选择了b。它应该返回'foo'还是'bar'

尽管MySQL 5.x允许您这样做,但它在MySQL 8或任何其他SQL方言中都不起作用。这是一种糟糕的做法,会产生意想不到的结果,更难维护,更容易出错,甚至MySQL也建议你不要这样做。(MySQL 5.x中甚至有一个选项可以禁止这种不明确的代码,但许多主机默认情况下不会激活它。(

因此,上述查询应该是以下查询之一。。。

SELECT a, b, SUM(c) FROM table GROUP BY a, b
-- or...
SELECT a, MAX(b), SUM(c) FROM table GROUP BY a
-- or...
SELECT a, MIN(b), SUM(c) FROM table GROUP BY a
-- etc, etc

在上面的例子中,没有一个是模棱两可的,也没有一个结果是任意的。


此外,不要使用,加入您的表格ANSI-92是用显式JOIN语法取代它的标准。它已经快30年了。这意味着你使用的语法已经过时三十年了。

例如,以下两个查询都是错误的,但只有后者会抛出一个错误,告诉它是错误的

SELECT * FROM a, b WHERE a.id = 1
-- vs
SELECT * FROM a JOIN b WHERE a.id = 1

当后一个查询抛出错误时,很容易进行更正。。。

SELECT * FROM a JOIN b ON b.a_id = a.id WHERE a.id = 1

总之,这意味着您的查询应该是…

select
e.student_num as StudentID,
s.student_name as Name,
sum(c.num_credits*450) as Tuition
from
students s
inner join
enrolls  e
on e.student_num = s.student_num
inner join
sections se
on se.section_id = e.section_id 
inner join
courses c 
on c.course_num = se.course_num
group by
s.student_num,
s.student_name

应该牢记发表评论的人的暗示。这将在未来为你省去很多痛苦。

下面是现代SQL方法的一个示例,其中包含一个完整的GROUP BY:

SELECT e.student_num as StudentID,
s.student_name as Name,
SUM(c.num_credits * 450) as Tuition 
FROM students s INNER JOIN enrolls e ON e.student_num = s.student_num
INNER JOIN sections se ON e.section_id = se.section_id
INNER JOIN courses c ON se.course_num = c.course_num
GROUP BY s.student_name;

最新更新