mysql 校验和,从MySQL的校验和表中选择并仅返回校验和(不是表)

When I run "mysql> CHECKSUM TABLE mytable;", I got the following result:

+------------------+------------+

| Table | Checksum |

+------------------+------------+

| mydb.mytable | 1679935596 |

+------------------+------------+

How to select and return only the Checksum (not Table) in the above result in one mysql statement?

Something like "SELECT Checksum FROM (CHECKSUM TABLE mytable);"??? Tried several times, but no idea.

What I want is:

+------------+

| Checksum |

+------------+

| 1679935596 |

+------------+

解决方案

You can do it by column, or sum of columns. Below is a test on a table of mine.

SELECT sum(crc32(email)) as crc from users;

+-------------+

| crc |

+-------------+

| 10679459550 |

+-------------+

select sum(crc32(concat(user_id,first_name,last_name,email,reportingManager))) as crc from users;

+------------+

| crc |

+------------+

| 7196315383 |

+------------+

Edit

In a stored procedure being passed a database name and a table name, the below will return the crc. It goes to the special INFORMATION_SCHEMA db to retrieve the column names for you, and uses all those columns and values to generate a checksum.

Stored procedure:

drop procedure if exists getTableCRC32;

DELIMITER $$

create procedure getTableCRC32

( dbname varchar(80),

tableName varchar(80)

)

BEGIN

set @sql1="select GROUP_CONCAT(`column_name` SEPARATOR ',') into @colNames";

set @sql1=concat(@sql1," FROM `INFORMATION_SCHEMA`.`COLUMNS`");

set @sql1=concat(@sql1," WHERE `TABLE_SCHEMA`='",dbName,"'");

set @sql1=concat(@sql1," AND `TABLE_NAME`='",tableName,"'");

-- select @sql1;

PREPARE stmt1 FROM @sql1;

EXECUTE stmt1;

DEALLOCATE PREPARE stmt1;

-- select @colNames;

set @sql2=concat( 'select sum(crc32(concat(', @colNames, '))) as crc from ',tableName);

-- select @sql2;

PREPARE stmt2 FROM @sql2;

EXECUTE stmt2;

DEALLOCATE PREPARE stmt2;

END

$$

DELIMITER ;

Test it:

call getTableCRC32('so_gibberish','users');

+------------+

| crc |

+------------+

| 7196315383 |

+------------+

call getTableCRC32('so_gibberish','fish');

+------------+

| crc |

+------------+

| 3273020843 |

+------------+

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值