MySQL statements related lessons learned

1. Field decrement

UPDATE `table_name` SET `total`=IF(`total` < 1, 0, `total`-1) WHERE `id` = 1;

In general when we do field subtraction require a value judgment on the outside

This will eliminate a query external value determination, also possible to prevent the total field unsigned overflow value is 0, the error becomes maximum or case

 


2. UPDATE's SET data using subqueries

UPDATE `bz_xs_chapter` AS c,
(SELECT COUNT(*) AS total FROM `bz_xs_chapter` WHERE `bookId` = 22042) AS c1,
(SELECT COUNT(*) AS total FROM `bz_xs_tome` WHERE `bookId` = 22372) AS c2
SET
`c`.`name`=`c1`.`total`, 
`c`.`words`=`c2`.`total` 
WHERE `c`.`id` = 2889820

This update multiple sub-queries by field value, the efficiency is much higher bar

 


High 3. COUNT (*) Efficiency

Before seen a lot of related posts, some say use COUNT (id) high efficiency, each side seems to have a reason, but they test:

270W data, 350MB size of the data table, COUNT (*) than  COUNT (id speed of at least 10 or 100 times)







Reproduced in: https: //my.oschina.net/zhouz/blog/213088

Guess you like

Origin blog.csdn.net/weixin_34161032/article/details/91728283