First, create a table to describe the problem.
Copy codeThe Code is as follows:
Create table 'result '(
'Name' varchar (20) default NULL,
'Subobject' varchar (20) default NULL,
'Score 'tinyint (4) default NULL
) ENGINE = MyISAM default charset = utf8
Insert some data,
Copy codeThe Code is as follows:
Insert into result values
('Zhang san', 'mat', 90 ),
('Zhang san', 'China', 50 ),
('Zhang san', 'geo', 40 ),
('Li si', 'China', 55 ),
('Li si', 'political ', 45 ),
('Wang 5', 'political ', 30 ),
('Zhao liu', 'language', 100 ),
('Zhao liu', 'mat', 99 ),
('Zhao liu', 'morality ', 98 );
Requirement: query the average score of two or more non-pass students.
Two query statements are often used:
Copy codeThe Code is as follows:
Select name, sum (score <60), avg (score) from result group by name having sum (score <60)> = 2;
Copy codeThe Code is as follows:
Select name, count (score <60 )! = 0) as a, avg (score) from result group by name having a> = 2;
The results of the two queries must be different. They must be the first correct one. The reason is why, now you have to think about the meaning of the count () function and the meaning of the sum function.
When the parameters in the count () function are column names, the number of times a value item is calculated.
When the parameters in the Sum () function are column names, they are used to calculate the Sum of column names, rather than the total number of values.
Pay attention to the number of count () rows: it calculates the total number of rows. Whether or not you have a value is included in the calculation range. Another point: The mysqlisam engine can easily obtain statistics on the total number of rows. Faster query speed
Summary: It is often used to count the total number of rows in actual programming. In this case, count (*) is used for multiple visibility. I rarely see the use of column names as parameters: count (. Even in this way, the original intention may be to count the number of rows. I just don't know! The form of "column name" is incorrect due to the slight difference.