前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MySQL中JSON数组的一点处理

MySQL中JSON数组的一点处理

原创
作者头像
一介程序员
修改2022-08-15 00:20:29
2.4K0
修改2022-08-15 00:20:29
举报

对于下面的表结构,一个用户表,一个角色表,用户表里面的role_id通过JSON格式保存角色id的数组。

代码语言:sql
复制
create table user(
	id int not null auto_increment primary key,
  name varchar(32) not null,
  role_id json not null
);
create table role(
	id int not null auto_increment primary key,
  name varchar(32) not null
);

insert into role(name) values ('部门1'),('部门2'),('部门3');
insert into user(name, role_id) values ('user1', '[1, 2]');
insert into user(name, role_id) values ('user2', '[2, 3]');
image-20220814234157852.png
image-20220814234157852.png

在开发中,希望返回用户信息的时候,将role_id中的id换成{id: 1, name: '部门1'} 这样的形式。

具体思路如下:

代码语言:sql
复制
select * 
from user join json_table(user.role_id, '$[*]' columns(rid int path '$')) as t;

select * 
from user join json_table(user.role_id, '$[*]' columns(rid int path '$')) as t 
left join role on role.id = t.rid;

select user.id, user.name, 
json_arrayagg(json_object('id', role.id, 'name', role.name)) as role
from user join json_table(user.role_id, '$[*]' columns(rid int path '$')) as t 
left join role on role.id = t.rid 
group by user.id;
image-20220815000324567.png
image-20220815000324567.png

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档