こんにちは!
プログラミングを始めてデータベースに触れていると、いつかこの問題に出くわすでしょう。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);
?>
したがって、DBには次のフィールドを作成する必要があります:
(一意、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.