1

Estoy diseñando una base de datos en MySQL (uso la versión 5.7.12 que ya tiene soporte nativo para JSON), y estoy evaluando las ventajas de usar JSON para almacenar una lista de etiquetas asociadas a un valor (en lugar de utilizar una segunda tabla relacionada para guardarlas). Mi idea es guardar un arreglo JSON con las etiquetas, y después seleccionar únicamente aquellos registros que contengan la etiqueta.

Mi pregunta es: ¿Cómo buscar eficientemente si existe un valor en el arreglo JSON?

Ejemplo (con tablas):

 create table tbl_perfil(
     id_perfil int unsigned not null primary key,
     nombre varchar(100)
 );
 create table tbl_perfil_tags(
     id_perfil int unsigned not null,
     tag varchar(100),
     primary key (id_perfil, tag)
 ); // Omito "CONSTRAINTS" por brevedad
 insert into tbl_perfil values 
     (1, "test"), (2, "test 2");
 insert into tbl_perfil_tags values 
     (1, "tag1"), (1, "tag2"),
     (2, "tag1"), (2, "tag3");
 select p.*, pt.tag
 from tbl_perfil as p
      inner join tbl_perfil_tags as pt using (id_perfil)
 where p.tag = "tag2";

 id_perfil | nombre | tag
 ----------+--------+-----
  1        | test   | tag2

Ejemplo 2 (con JSON):

 create table tbl_perfil (
     id int unsigned not null primary key,
     nombre varchar(100),
     etiquetas JSON
 );
insert into tbl_perfil values
    (1, 'test', '[{"etiqueta": "tag1"}, {"etiqueta": "tag2"}]'),
    (2, 'test2', '[{"etiqueta": "tag1"}, {"etiqueta": "tag3"}]');
select p.*
from tbl_perfil as p
where json_search(etiquetas, 'one','tag2') is not null;

id_perfil | nombre | etiquetas
----------+--------+----------------------------------------------
 1        | test   | [{"etiqueta": "tag1"}, {"etiqueta": "tag2"}]

Esta última consulta me da lo que necesito (e incluso más, porque me da todas las etiquetas que tiene el perfil)... pero ¿es la forma más eficiente (o correcta) de hacer esta búsqueda?

1 respuesta 1

1

Quizás pueda mejorar su búsqueda de la siguiente manera:

SELECT
  `id`,
  `nombre`,
  `etiquetas` 
FROM
  `tbl_perfil`
WHERE
  JSON_SEARCH(`etiquetas`, 'one', 'tag2', NULL, '$[*].etiqueta') IS NOT NULL;

Sin embargo, puede pensar en un diseño como el siguiente:

mysql> DROP TABLE IF EXISTS `tbl_perfil`;
Query OK, 0 rows affected (0,00 sec)

mysql> CREATE TABLE IF NOT EXISTS `tbl_perfil` (
    ->   `id` INT UNSIGNED NOT NULL PRIMARY KEY,
    ->   `nombre` VARCHAR(100),
    ->   `etiquetas` JSON
    -> );
Query OK, 0 rows affected (0,00 sec)

mysql> INSERT INTO `tbl_perfil`
    -> VALUES
    ->   (1, 'test', '["tag1", "tag2"]'),
    ->   (2, 'test2', '["tag1", "tag3"]');
Query OK, 2 rows affected (0,01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> SELECT
    ->   `id`,
    ->   `nombre`,
    ->   `etiquetas` 
    -> FROM
    ->   `tbl_perfil`
    -> WHERE
    ->   JSON_SEARCH(`etiquetas`, 'one', 'tag2') IS NOT NULL;
+----+--------+------------------+
| id | nombre | etiquetas        |
+----+--------+------------------+
|  1 | test   | ["tag1", "tag2"] |
+----+--------+------------------+
1 row in set (0,00 sec)

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.