Home  >  Article  >  Database  >  What is the usage of mysql count() function

What is the usage of mysql count() function

青灯夜游
青灯夜游Original
2022-03-01 15:54:5918958browse

In mysql, the COUNT() function can count the total number of record rows contained in the data table, or return the number of data rows contained in the column based on the query results; syntax "SELECT COUNT(*) FROM data table; ” or “SELECT COUNT(field name) FROM data table;”.

What is the usage of mysql count() function

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

MySQL COUNT() function counts the total number of record rows contained in the data table, or returns the number of data rows contained in the column based on the query results. There are two ways to use it:

  • COUNT(*) Calculate the total number of rows in the table, regardless of whether a column has a value or a null value.

  • COUNT (field name) Calculate the total number of rows under the specified column. Rows with null values ​​will be ignored during calculation.

Example 1: Query the total number of rows in the tb_students_score table

mysql> SELECT COUNT(*)
    -> AS students_number
    -> FROM tb_students_score;
+-----------------+
| students_number |
+-----------------+
|              10 |
+-----------------+
1 row in set (0.03 sec)

As you can see from the query results, COUNT(*) returns the total number of rows recorded in the tb_students_score table. No matter what the value is. The total number returned is named students_number.

Tip: The way NULL values ​​are treated when calculating totals is that rows with a null value in the specified column are ignored by the COUNT() function, but if the column is not specified, the COUNT() function If the asterisk "*" is used, all records will not be ignored.

Example 2: Return the number of products in the "Products" table

mysql> SELECT COUNT(ProductID) 
    -> AS NumberOfProducts 
    -> FROM Products;

+-----------------+
| NumberOfProducts|
+-----------------+
|              77 |
+-----------------+
1 row in set (0.03 sec)

[Related recommendations: mysql video tutorial]

The above is the detailed content of What is the usage of mysql count() function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn