scene
There is a table, which contains the grades of students and their corresponding courses. It is necessary to find courses that are greater than the average of all courses of the student.
Table structure
Solution
I think of two kinds of SQL, as follows
The first
Find out the average value corresponding to each student and connect it with the original table, and then compare the course score and average value with the query conditions
select t1.student_id,course_id
from t_mark t1,
(
SELECT student_id,AVG(mark) avg
from
t_mark
group by student_id
) t2
where t1.student_id = t2.student_id
and t1.mark > t2.avg
The second
Each time you use a subquery in the query condition to find out the student’s course average comparison
select t1.student_id,course_id
from t_mark t1
where t1.mark>
(select AVG(mark)
from t_mark t2
where t2. student_id = t1.student_id)
Compare two SQL
Data input
In order to have enough data for comparison, write a stored procedure to insert 3 pieces of score data for 3000 students
CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_to_mark`()
BEGIN
#Routine body goes here...
DECLARE i INTEGER;
SET i = 1;
WHILE i<=3000 DO
INSERT INTO t_mark
(student_id,course_id,mark)
VALUES
(i,1,RAND()*70+30),
(i,2,RAND()*70+30),
(i,3,RAND()*70+30);
set i = i+1;
END WHILE;
END
Inserted successfully
Query comparison
The first
The second
The gap is quite large.
in conclusion
It is better to use the first one. I don’t know if there is a more efficient query sql. Welcome to comment~~