学校表:

1 create table school(
2   `id`  bigint unsigned primary key not null auto_increment, 3   `name` varchar(10) not null, 4   `tagId` json 5 );

tagId字段为json数组,存有标签表中的id

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

标签表:

1 create table tag(
2    `id`  bigint unsigned primary key not null auto_increment, 3 `name` varchar(10) not null 4 );

在查询时,可以使用group_concat和concat函数手动拼接json:

select 
 *,
 (select concat('[',group_concat('{"id":',tag.id,',"name":"',tag.`name`,'"}'),']') from `tag` where json_contains(`school`.tagId, json_array(tag.id))) as `tag` from school limit 10

即可得到标签的信息,查询结果的tag字段为手动拼接的json数组

如果需要查询有特定的tagId的学校,可以使用json_contains函数:

select 
 *,
 (select concat('[',group_concat('{"id":',tag.id,',"name":"',tag.`name`,'"}'),']') from `tag` where json_contains(`school`.tagId, json_array(tag.id))) as `tag` from school where json_contains(tagId,json_array(1)) limit 10

这样即可得到有1号标签的学校列表

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄