Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

how to fetch data from two tables in mysql?

I have to find out the output as class name and number of students in each class? My both tables are-

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;

I was trying to return the required out from the following code but it does not return same. Any idea why it is not returning the right values.I am a beginner in MySql so I am unable to find out the problem.

SELECT class.Name , COUNT(student.name)
From class INNER JOIN student
    ON class.Fields_ID=student.Fields_ID;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using aggregate functions you should group them like GROUP BY class.Name so you will get the count of students in each class,other wise you will get a single row not the results per group i.e students per class

SELECT class.Name , COUNT(student.name)
From class INNER JOIN student
    ON class.Fields_ID=student.Fields_ID
GROUP BY class.Name;

GROUP BY (Aggregate) Functions

See fiddle demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...