The differences between count of and sum of in Mysql are described in detail

  • 2020-05-13 03:42:36
  • OfStack

Start by creating a table to illustrate the problem
 
CREATE TABLE `result` ( 
`name` varchar(20) default NULL, 
`subject` varchar(20) default NULL, 
`score` tinyint(4) default NULL 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 

Insert 1 bit of data,
 
insert into result values 
(' zhang 3',' mathematics ',90), 
(' zhang 3',' Chinese language and literature ',50), 
(' zhang 3',' geographic ',40), 
(' li 4',' Chinese language and literature ',55), 
(' li 4',' political ',45), 
(' The king 5',' political ',30) .  
(' zhao 6',' Chinese language and literature ',100), 
(' zhao 6',' mathematics ',99), 
(' zhao 6',' Moral character ',98); 

Requirements: find out the average score of those who failed 2 or more.
There are often two types of query statements:
 
select name,sum(score < 60) ,avg(score) from result group by name having sum(score<60) >=2; 

 
select name ,count((score<60)!=0) as a,avg(score) from result group by name having a >=2; 

The result of the two queries must be different, must be the first one right, and the reason is why, you have to think, what does count () mean and what does sum mean
When the parameter in the count() function is the column name, the number of entries is counted.
When the parameter in the Sum() function is the column name, it is the sum of the values of the column names, not the total number of values.
Note also for the number of lines count() : it counts the total. Whether you have a value or not will be counted. Another point: the mysqlisam engine can easily get statistics on the total number of rows. Queries become faster
Induction: the actual programming of the total number of statistics is often used. At this point, count(*) can be seen in multiple places. I rarely see anyone using the column name as a parameter :count(a). Even so, it may be intended to count the number of rows. I just don't know! This caused a slight difference and the "column name" form was misused.

Related articles: