你好!

如果你刚开始编程并接触数据库,总有一天你会遇到这个问题。在 MySQL 中,text 字段不能设为唯一,但有一个非常简单的解决方案,就是使用与该哈希等效的唯一标识符。

假设我们有以下长文本:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

如果我们使用 php 的 https://www.php.net/manual/es/function.md5.php 函数或 https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_md5 中的同名函数,就能得到以下唯一结果:

01aad0e51fcd5582b307613842e4ffe5

这样一来,我们就有了一个哈希值,可以用来验证它是否存在,而不会占用大量空间(加密会消耗更多 CPU,但不占用数据库空间)。

php 中的函数如下:

<?php
$string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
echo $string;
echo "<hr />";
echo md5($string);
?>

因此,在数据库中我们需要创建以下字段:

(唯一,varchar255)hash:01aad0e51fcd5582b307613842e4ffe5 (文本,不设为唯一)texto:Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.