Crear un campo "text" único en MySQL

avatar de thisjrodriguez
Publicado por thisjrodriguez el 08/05/2020 19:00
Debate 0 Respuestas

Hola!

Si estas comenzando a programar y a tocar las bases de datos, encontraras algún día este problema. Los campos text no pueden ser unicos en MySQL, pero tiene una solución muy simple qué es identificador único equivalente a ese hash.

Digamos que tenemos el siguiente texto largo:

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.

Si usamos la función md5 de php o la misma de MySQL, podremos tener el siguiente resultado único: 

01aad0e51fcd5582b307613842e4ffe5

De esta forma, tendríamos un hash para verificar si existe o no sin que ocupe un gran espacio (consume más CPU la encriptación, pero no espacio en base de datos).

La función en php quedaría así:

<?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);
?>

Por lo qué en la DB tendríamos que crear las siguientes campos:

(único, varchar255) hash: 01aad0e51fcd5582b307613842e4ffe5
(texto, sin identificarlo como único) 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.

 

Publicidad