안녕하세요!
프로그래밍을 시작하고 데이터베이스를 다루기 시작했다면, 언젠가 이 문제를 마주하게 될 것입니다. MySQL에서는 text 필드를 unique로 설정할 수 없지만, 해당 해시에 해당하는 고유 식별자를 사용하는 아주 간단한 해결책이 있습니다.
다음과 같은 긴 텍스트가 있다고 가정해 봅시다:
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.