We often use statistical data in applications, such as the number of current users (or the number of users meeting certain conditions), the maximum points of all users, and the average score of students, thinkPHP provides a series of built-in statistics queries for these statistics operations
We often use statistical data in applications, such as the number of current users (or the number of users meeting certain conditions), the maximum points of all users, and the average score of students. ThinkPHP
Provides a series of built-in methods for these statistical operations:
Count (): Number of statistical data rows
Max (): calculates the maximum data of a field.
Min (): calculates the minimum data of a field.
Avg (): calculates the average data of a field.
Sum (): calculates the sum of the data of a field.
The preceding statistical query methods are independent and support consistent operations.
Count ()
Count ()
The method is used to calculate the number of rows.
Example:
- Public function read (){
- $ Dao = M ('user ');
- // Obtain the number of users:
- $ UserCount = $ Dao-> count ();
- // Add conditions:
- $ UserCount2 = $ Dao-> where ('uid> 10')-> count ();
- $ This-> assign ('usercount', $ userCount );
- $ This-> display ();
- }
In the preceding example, the SQL statements actually executed by the two query statements are:
- Select count (*) AS tp_count FROM user LIMIT 1
- Select count (*) AS tp_count FROM user WHERE uid> 10 LIMIT 1
You can directly output the statistical data in the template:
Total users {$ userCount}
Person.
Max ()
The max () method is used to calculate the maximum data of a field.
Example of calculating the maximum user points:
- $ MaxScore = $ Dao-> max ('score ');
The actual executed SQL statement is:
- Select max (score) AS tp_max FROM user LIMIT 1
Min ()
Min ()
Calculates the minimum data of a field.
Example of getting the minimum credits of a user whose credits are greater than 0:
- $ MinScore = $ Dao-> where ('score> 0')-> min ('score ');
The actual executed SQL statement is:
- Actually executed SQL: SELECT MIN (score) AS tp_min FROM user WHERE score> 0 LIMIT 1
Avg ()
Avg ()
Calculate the average data of a field.
Example of getting average credits of a user:
- $ AvgScore = $ Dao-> avg ('score ');
The actual executed SQL statement is:
- Select avg (score) AS tp_avg FROM user LIMIT 1
Sum ()
Sum ()
Calculates the sum of the data of a field.
Calculate the sum of the points of the top 10 users in the points ranking:
- $ SumScore = $ Dao-> order ('score desc')-> limit ('10')-> avg ('score ');
The actual executed SQL statement is:
- Select sum (score) AS tp_sum FROM user order by score desc limit 1
All statistical queries, such as select ()
Same method. Consistent operations are supported, and different query conditions are added according to the actual situation.