mysql function if the proper use of gestures

- In order to write the contents of today, running for nearly seven hours of programs, 10 million pieces of data stored in the database. -
I say today is an example of IF mysql database () function.
Specifically scene follows,
take a look at the table structure:

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:系统通知,2:投诉建议',
  `status` int(1) DEFAULT NULL COMMENT '0:待发送,1:成功,2:失败',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Specific requirements are: statistics of the total number of complaints and suggestions notification system of two types of messages, the number of successful and failed several.

Encountered such a problem, we have the general idea is to use type groups, respectively, the total number of queries and complaints systems to inform recommendations, then two sub-queries to count the number of successes and failures of the number of pieces. sql 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

We look at run time statistics about 10 million pieces of data need 6 minutes and 18 seconds .
Is there a simpler, faster way of statistics, of course, is there, what we mainly talked about today if () function.

The basic syntax

The IF (expr1, expr2, expr3), if expr1 is true, the value is returned expr2 if expr1 is false, then the value returned expr3. It is a simple three-goal expression.

How to do

Talk about ideas, if we count the number of successful, we can write if (status = 1,1,0), so if status == 1, it returns 1, otherwise it returns 0. We then SUM () function will succeed in adding to the number of pieces.

Method to realize

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;

Saw that it was not better than the above sub-queries more concise, we take a look at run time, only 1 minute 30 seconds . It is not much faster.
Well, today you learn it?

If the article helpful, please remember to focus on points like yo ~
Welcome to my public concern number <Love it>, pushing daily technical articles for them to learn.

Guess you like

Origin www.cnblogs.com/zhixie/p/11790290.html