问题
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 |
+------------+
回答1:
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 |
+------------+
Manual page for crc32
回答2:
MySQL CHECKSUM TABLE
command performs a CRC-32 checksum on the every row in the table including the row metadata. There is one or more bytes of metadata preceding each row. I just happen to know that in this case there is one byte for this row and it will contain the number 253, or in hex 0xFD. So you can use following function:
SELECT CRC32(CONCAT(0xFD, 'mytable')) AS Checksum;
Reference.
来源:https://stackoverflow.com/questions/33897469/select-and-return-only-checksum-not-table-from-checksum-table-in-mysql