DEV Community

Edgar Rios Navarro
Edgar Rios Navarro

Posted on

MySQL usar tipo SET para validar

Cuando diseñamos un sistema y tenemos una lista restringida de opciones, el modelo ER nos mostrará una relación de 'muchos a muchos'.

Consideremos el caso de Usuario - Roles:

Image description

El diagrama nos indica que debemos crear tres tablas.


Como alternativa, en MySQL nos proporciona el tipo SET.

Image description

Dicho campo acepta ninguno, uno o más valores de la lista.

mysql> insert into user(email,name,password) 
values('a@greatsolutions.consulting','A','A');
Query OK, 1 row affected (0.04 sec)

mysql> insert into user(email,name,password,roles) 
values('b@greatsolutions.consulting','B','B','');
Query OK, 1 row affected (0.04 sec)

mysql> insert into user(email,name,password,roles) 
values('c@greatsolutions.consulting','C','C','editor,user');
Query OK, 1 row affected (0.04 sec)
Enter fullscreen mode Exit fullscreen mode

Por el contrario, nos da error cuando intentamos insertar un valor diferente.

mysql> insert into user(email,name,password,roles) 
values('d@greatsolutions.consulting','D','D','root');
ERROR 1265 (01000): Data truncated for column 'roles' at row 1
mysql>
Enter fullscreen mode Exit fullscreen mode

Documentación

https://dev.mysql.com/doc/refman/8.0/en/set.html

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay