列出MySQL JSON字段的所有数组元素

时间:2017-08-13 18:46:05

标签: mysql arrays json mysql-5.7

我有一个JSON字段来保存帖子的标签。

id:1, content:'...', tags: ["tag_1", "tag_2"]

id:2, content:'...', tags: ["tag_3", "tag_2"]

id:3, content:'...', tags: ["tag_1", "tag_2"]

我只想列出所有标签的流行程度(甚至没有它们):

tag_2:3,

tag_1:2,

tag_3:1

1 个答案:

答案 0 :(得分:2)

以下是设置:

create table t ( id serial primary key, content json);
insert into t set content = '{"tags": ["tag_1", "tag_2"]}';
insert into t set content = '{"tags": ["tag_3", "tag_2"]}';
insert into t set content = '{"tags": ["tag_1", "tag_2"]}';

如果您知道任何标记数组中的最大标记数,则可以使用UNION提取所有标记:

select id, json_extract(content, '$.tags[0]') AS tag from t 
union
select id, json_extract(content, '$.tags[1]') from t;

+----+---------+
| id | tag     |
+----+---------+
|  1 | "tag_1" |
|  2 | "tag_3" |
|  3 | "tag_1" |
|  1 | "tag_2" |
|  2 | "tag_2" |
|  3 | "tag_2" |
+----+---------+

您需要与最长数组中的标记数一样多的联合子查询。

然后,您可以将其放在派生表中并对其执行聚合:

select tag, count(*) as count
from ( 
    select id, json_extract(content, '$.tags[0]') as tag from t 
    union 
    select id, json_extract(content, '$.tags[1]') from t
) as t2
group by tag
order by count desc;

+---------+-------+
| tag     | count |
+---------+-------+
| "tag_2" |     3 |
| "tag_1" |     2 |
| "tag_3" |     1 |
+---------+-------+

如果您将标记存储在第二个表而不是JSON数组中,这将更容易:

create table tags ( id bigint unsigned, tag varchar(20) not null, primary key (id, tag));
insert into tags set id = 1, tag = 'tag_1';
insert into tags set id = 1, tag = 'tag_2';
insert into tags set id = 2, tag = 'tag_3';
insert into tags set id = 2, tag = 'tag_2';
insert into tags set id = 3, tag = 'tag_1';
insert into tags set id = 3, tag = 'tag_2';

select tag, count(*) as count 
from tags
group by tag
order by count desc;

+-------+-------+
| tag   | count |
+-------+-------+
| tag_2 |     3 |
| tag_1 |     2 |
| tag_3 |     1 |
+-------+-------+

无论您拥有多少个标签,此解决方案都可以使用。您不需要知道每个ID的标签列表的最大长度。

当您需要存储'文件时,JSON很不错。半结构化数据,但仅当您将文档视为一个不可减少的数据值时。只要您需要访问文档的元素并对它们应用关系操作,面向文档的方法就会显示出它的弱点。