Detailed explanation of the correct use of the if function in MySQL

Detailed explanation of the correct use of the if function in MySQL

For what I am going to write today, the program ran for nearly 7 hours and stored 10 million pieces of data in the database. ——

What I want to talk about today is an example of the IF() function of the MySQL database.

The specific scenarios are as follows:

Let's take a look at the table structure first:

CREATE TABLE `message` (
 `id` varchar(30) NOT NULL,
 `title` varchar(30) DEFAULT NULL,
 `content` text,
 `send_time` datetime DEFAULT NULL,
 `type` int(1) DEFAULT NULL COMMENT '1: system notification, 2: complaint suggestion',
 `status` int(1) DEFAULT NULL COMMENT '0: waiting to be sent, 1: success, 2: failure',
 PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

The specific requirements are: to count the total number, successful number and failed number of system notifications and complaint suggestions respectively.

When encountering such a problem, our general idea is to use type grouping to query the total number of system notifications and complaints and suggestions respectively, and then use two subqueries to count the number of successful and failed items. The sql is as follows:

SELECT
 COUNT(1) total,
 m.type,
 (SELECT
   COUNT(1)
  FROM message ms
  WHERE ms.status = 1
    AND m.type = ms.type) successtotal,
 (SELECT
   COUNT(1)
  FROM message mf
  WHERE mf.status = 1
    AND m.type = mf.type) failtotal
FROM message m
GROUP BY m.type

Let's take a look at the running time. It takes about 6 minutes and 18 seconds to count 10 million pieces of data.

So is there a simpler and faster way to count? Of course there is, and that is the if() function we are mainly talking about today.

Basic syntax

IF(expr1, expr2, expr3) returns the value of expr2 if the value of expr1 is true, and returns the value of expr3 if the value of expr1 is false. It is a simple ternary expression.

How to do it

Let's talk about the idea. If we count the number of successful results, we can write if(status=1,1,0) like this. If status==1, it returns 1, otherwise it returns 0. Then we can add up the number of successful results using the SUM() function.

Implementation

The sql statement is as follows:

SELECT
 COUNT(1) total,
 m.type,
 SUM(IF(m.status = 1,1,0)) successtotal,
 SUM(IF(m.status != 1,1,0)) failtotal
FROM message m
GROUP BY m.type;

Doesn’t it look much simpler than the subquery above? Let’s take a look at the running time, which is only 1 minute and 30 seconds. Isn't it much faster?

So, have you learned it today?

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Summary of knowledge points related to null (IFNULL, COALESCE and NULLIF) in MySQL
  • Summary of coalesce() usage tips in MySQL
  • Detailed explanation of IFNULL() and COALESCE() functions to replace null in MySQL
  • SQL Server COALESCE Function Detailed Explanation and Examples
  • A brief analysis of the performance comparison between the paging modes ISNULL and COALESCE in SQL Server
  • MySQL time difference functions (TIMESTAMPDIFF, DATEDIFF), date conversion calculation functions (date_add, day, date_format, str_to_date)
  • MySQL uses custom functions to recursively query parent ID or child ID
  • MySql COALESCE function usage code example

<<:  Detailed explanation of Nginx configuration parameters in Chinese (load balancing and reverse proxy)

>>:  How does WeChat Mini Program obtain user information and user phone number at the same time

Recommend

Detailed explanation of rpm installation in mysql

View installation and uninstallation # View rpm -...

How to install MySQL 5.7.28 binary mode under CentOS 7.4

Linux system version: CentOS7.4 MySQL version: 5....

An example of how to write a big sun weather icon in pure CSS

Effect The effect diagram is as follows Implement...

The process of using vxe-table to make editable tables in vue

There is a table in the project that needs to be ...

CentOS 7 installation and configuration tutorial under VMware10

If Ubuntu is the most popular Linux operating sys...

How to export mysql table structure to excel

The requirements are as follows Export the table ...

Summary of the use of Vue computed properties and listeners

1. Computed properties and listeners 1.1 Computed...

CSS and HTML and front-end technology layer diagram

Front-end technology layer (The picture is a bit e...

How to submit a pure HTML page, pass parameters, and verify identity

Since the project requires a questionnaire, but th...

Detailed explanation of anonymous slots and named slots in Vue

Table of contents 1. Anonymous slots 2. Named slo...

JS calculates the probability of winning based on the prize weight

Table of contents 1. Example scenario 1.1. Set th...

How to maintain a long connection when using nginx reverse proxy

· 【Scene description】 After HTTP1.1, the HTTP pro...

Simple setup of VMware ESXi6.7 (with pictures and text)

1. Introduction to VMware vSphere VMware vSphere ...