MySQL Check Sum

10 阅读2分钟

Table

介绍 function 前先展示用到的 table

CREATE TABLE `city` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` char(35) NOT NULL DEFAULT '',
  `CountryCode` char(3) NOT NULL DEFAULT '',
  `District` char(20) NOT NULL DEFAULT '',
  `Population` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`),
  KEY `CountryCode` (`CountryCode`) BLOCK_SIZE 16384 LOCAL
) AUTO_INCREMENT = 2000002 DEFAULT CHARSET = utf8mb4 ROW_FORMAT = DYNAMIC COMPRESSION = 'zstd_1.3.8' REPLICA_NUM = 1 BLOCK_SIZE = 16384 USE_BLOOM_FILTER = FALSE TABLET_SIZE = 134217728 PCTFREE = 0

查询表中数据:select * from city c where id in (1,2,3) ;

ID|Name    |CountryCode|District|Population|
--+--------+-----------+--------+----------+
 1|Kabul   |AFG        |Kabol   |   1780000|
 2|Qandahar|AFG        |Qandahar|    237500|
 3|Herat   |AFG        |Herat   |    186800|

CONCAT_WS

CONCAT_WS() 函数,concat with sperator,** **是 CONCAT() 的特殊形式。第一个参数是其它参数的分隔符。分隔符放在要连接的两个字符串之间。分隔符可以是一个字符串,也可以是其它参数。如果分隔符为 NULL,则结果为 NULL。函数会忽略任何分隔符参数后的 NULL 值。但是CONCAT_WS()不会忽略任何空字符串。 (然而会忽略所有的 NULL), CONCAT()是直接连接所有字符串,其中任何一个参数为 null 时,结果为 null

SELECT CONCAT_WS('#',c.ID,  c.Name , c.CountryCode)
FROM city c where  id in (1,2,3);
CONCAT_WS('#',c.ID,  c.Name , c.CountryCode)|
--------------------------------------------+
1#Kabul#AFG                                 |
2#Qandahar#AFG                              |
3#Herat#AFG                                 |

CRC32

CRC32()函数,CRC32 是一个非加密算法,容易产生 hash 碰撞,它更快,比 MD5 和 SHA1 占用更少 CPU 。

SELECT CRC32(CONCAT_WS('#',ID , c.Name , c.CountryCode))
FROM city c where id in (1,2,3) ;
CRC32(CONCAT_WS('#',ID , c.Name , c.CountryCode))|
-------------------------------------------------+
                                       4040106105|
                                         74740597|
                                       3127749511|

BIT_XOR

BIT_XOR () 函数,BIT_XOR 是一个位异或运算, 对所有行异或运算得出一个结果

SELECT BIT_XOR(CAST(CRC32(CONCAT_WS('#',ID , c.Name , c.CountryCode)) AS UNSIGNED)) 
FROM city c where id in (1,2,3) ;
BIT_XOR(CAST(CRC32(CONCAT_WS('#',ID , c.Name , c.CountryCode)) AS UNSIGNED))|
----------------------------------------------------------------------------+
1322711179|

MySQL: String function

dev.mysql.com/doc/refman/…

MySQL: Aggregate Function Descriptions

dev.mysql.com/doc/refman/…

Pt-table-checksum

www.percona.com/blog/2014/1…