Home Database Mysql Tutorial what is mysql count

what is mysql count

Apr 03, 2023 pm 03:45 PM
mysql count

mysql count is an aggregate function used to return the number of rows matching specified matching conditions; the syntax of the count function is such as "select count(*) from user;", which means counting all records, including NULL.

what is mysql count

#This tutorial Operating environment: Windows 10 system, mysql8 version, Dell G3 computer.

What is mysql count?

MySql statistical function COUNT detailed explanation

1. COUNT() function overview

COUNT() is a Aggregation function that returns the number of rows matching specified conditions. In development, it is often used to count the data in the table, all data, not NULL data, or to remove duplicate data.

#2. COUNT() parameter description

COUNT(1): Count records that are not NULL.

COUNT(*): Count all records (including NULL).

COUNT(field): Count the records whose "field" is not NULL.

  • If this field is defined as not null, read this field from the record line by line, judge that it cannot be null, and accumulate it line by line.

  • If this field definition allows null, it is judged that it may be null, and the value must be taken out and judged. If it is not null, it will be accumulated.

COUNT(DISTINCT field): Count the records where the "field" is deduplicated and is not NULL.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

-- MySql统计函数count测试

-- 创建用户表,新增测试数据

CREATE TABLE `user` (

  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID主键',

  `name` varchar(64) DEFAULT NULL COMMENT '姓名',

  `sex` varchar(8) DEFAULT NULL COMMENT '性别',

  `age` int(4) DEFAULT NULL COMMENT '年龄',

  `born` date DEFAULT NULL COMMENT '出生日期',

  PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='用户表';

 

INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (1, '%张三%', '男', 22, '2022-04-22');

INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (2, '李四', '女', 12, '2022-04-01');

INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (3, '王小二', '女', 12, '2022-04-28');

INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (4, '赵四', '男', 23, '2022-04-28');

INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (5, '', '女', 23, '2022-04-28');

INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (6, NULL, '女', 60, '2022-04-28');

INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (7, NULL, '女', 61, '2022-04-28');

 

select * from user;

 

-- 统计数据:7条数据,统计所有的记录(包括NULL)。

select count(*) from user;

 

-- 统计数据:7条数据,统计不为NULL 的记录。

select count(1) from user;

 

-- 统计数据:5条数据,COUNT(字段):统计该"字段"不为NULL 的记录,注意是null不是空''字符串

select count(name) from user;

 

-- 统计数据:5条数据,COUNT(DISTINCT 字段):统计该"字段"去重且不为NULL 的记录。

select count(distinct name) from user;

Copy after login

3. COUNT() determines the existence

SQL no longer uses count, but instead uses LIMIT 1, so that when the database query encounters one, it will return. Do not If you continue to search for how many items there are, you can directly determine whether it is non-empty in the business code.

select 1 from emp LIMIT 1; The efficiency is the highest, especially the need to limit the number of rows, which is easy to ignore.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

-- SQL查找是否"存在"

-- 员工表,存在则进行删除

drop table if EXISTS emp;

create table emp(

    id int unsigned primary key auto_increment,

    empno mediumint unsigned not null default 0,

    empname varchar(20) not null default "",

    job varchar(9) not null default "",

    mgr mediumint unsigned not null default 0,

    hiredate datetime not null,

    sal decimal(7,2) not null,

    comn decimal(7,2) not null,

    depno mediumint unsigned not null default 0

);

 

-- 新增cehsi数据

测试数据:https://blog.csdn.net/m0_37583655/article/details/124385347

 

-- cahxun

select * from emp ;

 

-- 时间:1.082s,数据:5000000

explain select count(*) from emp;

 

id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra

1     SIMPLE                                        Select tables optimized away

 

-- 时间:1.129s,数据:5000000

explain select count(1) from emp;

id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra

1     SIMPLE                Select tables optimized away

 

-- 时间:1.695s,数据:5000000

explain select 1 from emp;

id  select_type table   partitions  type    possible_keys   key  key_len    ref rows      filtered  Extra

1     SIMPLE            emp     idx_emp_depno   3 4981060   100.00  Using index

 

-- SQL不再使用count,而是改用LIMIT 1,让数据库查询时遇到一条就返回,不要再继续查找还有多少条了,业务代码中直接判断是否非空即可

-- 时间:0.001s,数据:5000000

explain select 1 from emp LIMIT 1;

id  select_type table   partitions  type    possible_keys   key key_len ref rows      filtered  Extra

1     SIMPLE            emp     idx_emp_depno       3   4981060     100.00  Using index

Copy after login

4. COUNT() Alibaba development specifications

1. [Mandatory] Do not use count (column name) or count (constant) To replace count(

), count() is the standard syntax for counting rows defined by SQL92. It has nothing to do with the database, and has nothing to do with NULL or non-NULL. Note: count(*) will count rows with NULL values. , and count (column name) will not count rows with NULL values ​​in this column.

2. [Mandatory] count(distinct col) calculates the number of unique rows in this column except NULL. Note that count( distinct col1, col2) If one of the columns is all NULL, then even if the other column has a different value, it will return 0.

what is mysql count

[Related recommendations:

mysql video Tutorial

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

Statement of this 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
When might a full table scan be faster than using an index in MySQL? When might a full table scan be faster than using an index in MySQL? Apr 09, 2025 am 12:05 AM

Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

Can I install mysql on Windows 7 Can I install mysql on Windows 7 Apr 08, 2025 pm 03:21 PM

Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

Can mysql and mariadb coexist Can mysql and mariadb coexist Apr 08, 2025 pm 02:27 PM

MySQL and MariaDB can coexist, but need to be configured with caution. The key is to allocate different port numbers and data directories to each database, and adjust parameters such as memory allocation and cache size. Connection pooling, application configuration, and version differences also need to be considered and need to be carefully tested and planned to avoid pitfalls. Running two databases simultaneously can cause performance problems in situations where resources are limited.

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

See all articles