In mysql, you can use the SELECT statement to query data, and use the COUNT() function to count the number of query results. The syntax is "SELECT COUNT(*) FROM table name [...];" or "SELECT COUNT (field name) FROM table name[...];".
The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.
In mysql, you can use the SELECT statement to query data, and use the COUNT() function to count the number of query results. The syntax format of
SELECT is as follows:
SELECT
{* | <字段列名>}
[
FROM <表 1>, <表 2>…
[WHERE <表达式>
[GROUP BY <group by definition>
[HAVING <expression> [{<operator> <expression>}…]]
[ORDER BY <order by definition>]
[LIMIT[<offset>,] <row count>]
]
Copy after login
Among them, the meaning of each clause is as follows:
{*|<Field column name>}A field list containing the asterisk wildcard character, indicating the name of the field to be queried.
##
,
…, Table 1 and Table 2 represent the source of query data, which can be single or multiple.
WHERE is optional. If selected, the query data must meet the query conditions.
GROUP BY< Field >, this clause tells MySQL how to display the queried data and group it according to the specified field.
##[ORDER BY< field>]
, this clause tells MySQL in what order to display the queried data, the sorting that can be done is in ascending order ( ASC) and descending (DESC), which is ascending by default.
##[LIMIT[,]]
, this clause tells MySQL to display the number of queried data items each time.
COUNT()
The 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
COUNT(*)
Calculate the total number of rows in the table, regardless of whether a column has a value or a null value.
COUNT(expression)
Counts the number of rows that do not contain a
NULL value.
COUNT(DISTINCT expression)
Returns the number of unique rows that do not contain a
NULL value## The return type of the #COUNT() function is
BIGINT
. If no matching row is found, the COUNT() function returns
0
. MySQL COUNT exampleLet’s create a new table named
demo
and insert some sample data.
USE testdb;
-- create a demos table
CREATE TABLE IF NOT EXISTS demos(
id int auto_increment primary key,
val int
);
-- insert some sample data
INSERT INTO demos(val)
VALUES(1),(1),(2),(2),(NULL),(3),(4),(NULL),(5);
-- select data from demos table
SELECT * FROM demos;
Copy after login
Execute the above query statement and get the following results-<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">+----+------+
| id | val |
+----+------+
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
| 4 | 2 |
| 5 | NULL |
| 6 | 3 |
| 7 | 4 |
| 8 | NULL |
| 9 | 5 |
+----+------+
9 rows in set</pre><div class="contentsignin">Copy after login</div></div>To count all rows in the
demos
table, please use
COUNT(*)
function, as shown below: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">mysql> SELECT COUNT(*) FROM demos;
+----------+
| COUNT(*) |
+----------+
| 9 |
+----------+
1 row in set</pre><div class="contentsignin">Copy after login</div></div> You can add a WHERE clause to specify a condition to count, for example, count only
val
columns that contain values equal to ## For rows #2, use the following query:
mysql> SELECT COUNT(*) FROM demos WHERE val = 2;
+----------+
| COUNT(*) |
+----------+
| 2 |
+----------+
1 row in set
Copy after login
If the val column is specified in the COUNT function, the
COUNT function counts All rows whose val column contains only non-NULL values. See the following query: Two NULL values in the
SELECT COUNT(*) FROM demos WHERE val = 2;
Copy after login
val column will be ignored.
To count the unique rows in the demos table, you can add the DISTINCT
operator to the
COUNT function, as in the following query statement:
SELECT COUNT(DISTINCT val) FROM demos;
Copy after login
Execute the above query statement and get the following results-
mysql> SELECT COUNT(DISTINCT val) FROM demos;
+---------------------+
| COUNT(DISTINCT val) |
+---------------------+
| 5 |
+---------------------+
1 row in set
Copy after login
Ignore the two duplicate values 1,
2
and two
in the count NULL value. MySQL COUNT with GROUP BYWe often use the COUNT
function in combination with the
GROUP BY
clause to count data in different groups. See the structure of the
products table below -
mysql> desc products;
+--------------------+---------------+------+-----+---------+------------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+---------------+------+-----+---------+------------------+
| productCode | varchar(15) | NO | PRI | | |
| productName | varchar(70) | NO | MUL | NULL | |
| productLine | varchar(50) | NO | MUL | NULL | |
| productScale | varchar(10) | NO | | NULL | |
| productVendor | varchar(50) | NO | | NULL | |
| productDescription | text | NO | | NULL | |
| quantityInStock | smallint(6) | NO | | NULL | |
| buyPrice | decimal(10,2) | NO | | NULL | |
| MSRP | decimal(10,2) | NO | | NULL | |
| stockValue | double | YES | | NULL | STORED GENERATED |
+--------------------+---------------+------+-----+---------+------------------+
10 rows in set
Copy after login
For example, to find the number of products in each product line, you can use the COUNT function with GROUP BY clause, as shown in the following query:
SELECT productline, count(*) FROM products GROUP BY productline;
Copy after login
Execute the above code and get the following results -
mysql> SELECT productline, count(*) FROM products GROUP BY productline;
+------------------+----------+
| productline | count(*) |
+------------------+----------+
| Classic Cars | 38 |
| Motorcycles | 13 |
| Planes | 12 |
| Ships | 9 |
| Trains | 3 |
| Trucks and Buses | 11 |
| Vintage Cars | 24 |
+------------------+----------+
7 rows in set
Copy after login
To find the product quantity provided by the supplier, please use the following query:
SELECT productvendor, count(*) FROM products GROUP BY productvendor;
Copy after login
Execute the above code and get the following results-
mysql> SELECT productvendor, count(*) FROM products GROUP BY productvendor;
+---------------------------+----------+
| productvendor | count(*) |
+---------------------------+----------+
| Autoart Studio Design | 8 |
| Carousel DieCast Legends | 9 |
| Classic Metal Creations | 10 |
| Exoto Designs | 9 |
| Gearbox Collectibles | 9 |
| Highway 66 Mini Classics | 9 |
| Min Lin Diecast | 8 |
| Motor City Art Classics | 9 |
| Red Start Diecast | 7 |
| Second Gear Diecast | 8 |
| Studio M Art Models | 8 |
| Unimax Art Galleries | 8 |
| Welly Diecast Productions | 8 |
+---------------------------+----------+
13 rows in set
Copy after login
To find which supplier provides at least
9
products, you can use the
HAVING
clause in
COUNT function, as shown in the following query statement:
SELECT productvendor, count(*) FROM products GROUP BY productvendor
HAVING count(*) >= 9;
Copy after login
Execute the above code and get the following results -
mysql> SELECT productvendor, count(*) FROM products GROUP BY productvendor
HAVING count(*) >= 9;
+--------------------------+----------+
| productvendor | count(*) |
+--------------------------+----------+
| Carousel DieCast Legends | 9 |
| Classic Metal Creations | 10 |
| Exoto Designs | 9 |
| Gearbox Collectibles | 9 |
| Highway 66 Mini Classics | 9 |
| Motor City Art Classics | 9 |
+--------------------------+----------+
6 rows in set
Copy after login
MySQL COUNT IFcan be used# Control flow functions in the ##COUNT
function, such as
IF
,
IFNULL
, CASE, etc. to count rows whose values match the condition. For example, the following query can find how many canceled, suspended and disputed orders: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">SELECT COUNT(IF(status=&#39;Cancelled&#39;,1, NULL)) &#39;Cancelled&#39;,
COUNT(IF(status=&#39;On Hold&#39;,1, NULL)) &#39;On Hold&#39;,
COUNT(IF(status=&#39;Disputed&#39;,1, NULL)) &#39;Disputed&#39;
FROM orders;</pre><div class="contentsignin">Copy after login</div></div>Execute the above code and get the following results-<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">mysql> SELECT COUNT(IF(status=&#39;Cancelled&#39;,1, NULL)) &#39;Cancelled&#39;,
COUNT(IF(status=&#39;On Hold&#39;,1, NULL)) &#39;On Hold&#39;,
COUNT(IF(status=&#39;Disputed&#39;,1, NULL)) &#39;Disputed&#39;
FROM orders;
+-----------+---------+----------+
| Cancelled | On Hold | Disputed |
+-----------+---------+----------+
| 6 | 4 | 3 |
+-----------+---------+----------+
1 row in set</pre><div class="contentsignin">Copy after login</div></div>If the status of the order Canceled, reserved or disputed, the IF function will return 1<p>, otherwise </p>NULL<p> will be returned. The </p>COUNT<p> function only counts <code>1, not NULL values, so the query returns the number of orders based on the corresponding status. [Related recommendations: mysql video tutorial]
The above is the detailed content of How to query and count the quantity in mysql. For more information, please follow other related articles on the PHP Chinese website!
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