Home  >  Article  >  Database  >  How to query and count the quantity in mysql

How to query and count the quantity in mysql

青灯夜游
青灯夜游Original
2021-12-07 11:32:5841795browse

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[...];".

How to query and count the quantity in mysql

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>]
]

Among them, the meaning of each clause is as follows:

  • {*|b44f51d0b443c93502271d3d391e4df2}A field list containing the asterisk wildcard character, indicating the name of the field to be queried.

  • ##05cee8b6ad5efd33489a0be0260a7bbc, a31a6b5c4a9ac86f75409c3950db0e23…, Table 1 and Table 2 represent the source of query data, which can be single or multiple.

  • WHERE ffbeece48539e6983ff3249db04f27c9 is optional. If selected, the query data must meet the query conditions.

  • GROUP BY3b26370eed070b4e2af74808aa8f2dee, this clause tells MySQL how to display the queried data and group it according to the specified field.

  • ##[ORDER BY0f5333100010744a1571ca8552350494]

    , 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[ab76cfca1a1dc7ff1291dcdf873f72ec,]bc984d207842008469e14f06321b6461]
  • , 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;

Execute the above query statement and get the following results-<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>To count all rows in the

demos

table, please use

COUNT(*)

function, as shown below: <pre class="brush:js;toolbar:false;">mysql&gt; SELECT COUNT(*) FROM demos; +----------+ | COUNT(*) | +----------+ | 9 | +----------+ 1 row in set</pre> 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
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;
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;
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
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
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;
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
To find the product quantity provided by the supplier, please use the following query:
SELECT productvendor, count(*) FROM products GROUP BY productvendor;

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

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;
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
MySQL COUNT IF

can 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: <pre class="brush:js;toolbar:false;">SELECT COUNT(IF(status=&amp;#39;Cancelled&amp;#39;,1, NULL)) &amp;#39;Cancelled&amp;#39;, COUNT(IF(status=&amp;#39;On Hold&amp;#39;,1, NULL)) &amp;#39;On Hold&amp;#39;, COUNT(IF(status=&amp;#39;Disputed&amp;#39;,1, NULL)) &amp;#39;Disputed&amp;#39; FROM orders;</pre>Execute the above code and get the following results-<pre class="brush:js;toolbar:false;">mysql> SELECT COUNT(IF(status=&amp;#39;Cancelled&amp;#39;,1, NULL)) &amp;#39;Cancelled&amp;#39;, COUNT(IF(status=&amp;#39;On Hold&amp;#39;,1, NULL)) &amp;#39;On Hold&amp;#39;, COUNT(IF(status=&amp;#39;Disputed&amp;#39;,1, NULL)) &amp;#39;Disputed&amp;#39; FROM orders; +-----------+---------+----------+ | Cancelled | On Hold | Disputed | +-----------+---------+----------+ | 6 | 4 | 3 | +-----------+---------+----------+ 1 row in set</pre>If the status of the order Canceled, reserved or disputed, the IF function will return

1

, otherwise

NULL

will be returned. The

COUNT

function only counts 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!

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