我必须找出每个班级的班级名称和学生人数?我的两张桌子都是 -
CREATE TABLE student(Fields_ID INT, Name VARCHAR(20));
INSERT INTO student(Fields_ID,Name) VALUES(30,'JYOTI');
INSERT INTO student(Fields_ID,Name) VALUES(31,'KIRTI');
INSERT INTO student(Fields_ID,Name) VALUES(32,'YOGITA');
INSERT INTO student(Fields_ID,Name) VALUES(33,'RASHMI');
INSERT INTO student(Fields_ID,Name) VALUES(34,'NUPUR');
SELECT * FROM student;
CREATE TABLE class(Fields_ID INT, Name VARCHAR(20));
INSERT INTO class(Fields_ID,Name) VALUES(30,'FIRST');
INSERT INTO class(Fields_ID,Name) VALUES(31,'SECOND');
INSERT INTO class(Fields_ID,Name) VALUES(32,'THIRD');
INSERT INTO class(Fields_ID,Name) VALUES(33,'FOURTH');
INSERT INTO class(Fields_ID,Name) VALUES(34,'FIFTH');
SELECT * FROM class;
我试图从以下代码返回所需的内容,但它不会返回相同的内容。 知道为什么它没有返回正确的值。我是MySql的初学者,所以我无法找出问题。
SELECT class.Name , COUNT(student.name)
From class INNER JOIN student
ON class.Fields_ID=student.Fields_ID;
答案 0 :(得分:3)
使用聚合函数,你应该像GROUP BY class.Name
一样对它们进行分组,这样你就可以得到每个班级的学生数量,另外你会得到一行而不是每组的结果,即每班学生
SELECT class.Name , COUNT(student.name)
From class INNER JOIN student
ON class.Fields_ID=student.Fields_ID
GROUP BY class.Name;