如何从两个以上的表中获取数据?

时间:2014-02-23 17:21:31

标签: mysql

我必须将得分超过总体平均成绩的学生数量作为输出。

以下是我的两张表:

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 Marks(Fields_ID INT, Student_ID INT NOT NULL,marks INT NOT NULL);
        INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (30,40,100);
        INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (31,41,88);
        INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (32,42,72);
        INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (33,43,33);
        INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (34,44,15);
SELECT * FROM Marks;

这是我试图返回我想要的输出的代码,但我无法形成正确的语法。

SELECT COUNT(student.name)
From student INNER JOIN Marks
    ON Marks.Fields_ID = student.Fields_ID
HAVING marks>AVG(marks);

我应该怎么做呢?

1 个答案:

答案 0 :(得分:1)

尝试这种方式:

SELECT COUNT(student.name)
From student 
INNER JOIN Marks
    ON Marks.Fields_ID = student.Fields_ID
WHERE Marks.marks>( SELECT AVG(marks)
                    FROM marks );

演示:http://sqlfiddle.com/#!2/0dd8ad/3