大家好我对SQL查询有问题:问题是如果我添加GROUP BY
数据库引擎输出错误:
Column 'dbo.classes.class_name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
我的查询是:
string query = "SELECT p.*
FROM dbo.classes AS p INNER JOIN teacher_classes AS a
ON a.class_id = p.class_id
and teach_id = @id
GROUP BY p.class_id";
请为此提供任何帮助。
请注意,查询工作没有组,但结果没有分组。
答案 0 :(得分:4)
您的查询是:
SELECT p.*
FROM dbo.classes AS p INNER JOIN
teacher_classes AS a
ON a.class_id = p.class_id and teach_id = @id
GROUP BY p.class_name;
您正在尝试从p中选择 all 列,但您正在按class_name进行分组。大多数数据库都不允许这样做。如果您有两个课程会发生什么,但信息与他们不同?
一种选择是使用distinct
而不是group by
来删除重复项:
SELECT distinct c.*
FROM dbo.classes c INNER JOIN
teacher_classes tc
ON tc.class_id = c.class_id and tc.teach_id = @id;
另一个选择是使用类似in
的内容来查找教师的匹配类:
select c.*
from classes c
where c.class_id in (select tc.class_id from teacher_classes where teach_id = @id)
注意我还更改了别名,因此它们与表名有一些关系。这使查询更容易阅读。