如何在mysql中组织Json中Json存储的多对多关系

时间:2018-04-03 12:55:02

标签: mysql json many-to-many

我有JSON字段的表(示例)

# table1

id | json_column
---+------------------------
1  | {'table2_ids':[1,2,3], 'sone_other_data':'foo'}
---+------------------------
2  | {'foo_data':'bar', 'table2_ids':[3,5,11]}

并且

# table2

id | title
---+------------------------
1  | title1
---+------------------------
2  | title2
---+------------------------
...
---+------------------------
11 | title11

是的,我知道第三个表中存储的多对多关系。但它是一个重复数据(第一种情况是Json_column中的关系,第三种情况下是第二种)

我知道MySQL中生成的列,但我不明白如何将它用于存储的m2m关系。也许我使用views来获取table1.id< - >对table2.id。但是在这种情况下如何使用索引?

1 个答案:

答案 0 :(得分:0)

我无法理解您为何不能使用第三个表来表示多对多对的解释。使用第三个表当然是最好的解决方案。

我认为观点与此问题无关。

您可以使用JSON_EXTRACT()来访问数组的各个成员。您可以使用生成的列拉出每个成员,以便您可以轻松地将其作为单个值引用。

create table table1 (
  id int auto_increment primary key,
  json_column json,
  first_table2_id int as (json_extract(json_column, '$.table2_ids[0]'))
);

insert into table1 set json_column = '{"table2_ids":[1,2,3], "sone_other_data":"foo"}'

(您必须在JSON字符串中使用双引号,并使用单引号来分隔整个JSON字符串。)

select * from table1;
+----+-----------------------------------------------------+-----------------+
| id | json_column                                         | first_table2_id |
+----+-----------------------------------------------------+-----------------+
|  1 | {"table2_ids": [1, 2, 3], "sone_other_data": "foo"} |               1 |
+----+-----------------------------------------------------+-----------------+

但这仍然是一个问题:在SQL中,表必须具有由表元数据定义的列,因此所有行都具有相同的列。没有基于数据填充其他列的每一行。

因此,您需要为table2_ids数组的每个潜在成员创建另一个额外列。如果数组的元素少于列数,则当表达式不返回任何内容时,JSON_EXTRACT()将填充NULL。

alter table table1 add column second_table2_id int as (json_extract(json_column, '$.table2_ids[1]'));
alter table table1 add column third_table2_id int as (json_extract(json_column, '$.table2_ids[2]'));
alter table table1 add column fourth_table2_id int as (json_extract(json_column, '$.table2_ids[3]'));

我将使用垂直输出进行查询,因此列更容易阅读:

select * from table1\G
*************************** 1. row ***************************
              id: 1
     json_column: {"table2_ids": [1, 2, 3], "sone_other_data": "foo"}
 first_table2_id: 1
second_table2_id: 2
 third_table2_id: 3
fourth_table2_id: NULL

这将变得非常尴尬。你需要多少列?这取决于有多少table2_ids是数组的最大长度。

如果你需要在table1中搜索引用某个特定table2 id的行,你应该搜索哪一列?任何列都可能具有该值。

select * from table1
where first_table2_id = 2
or second_table2_id = 2
or third_table2_id = 2
or fourth_table2_id = 2;

您可以在每个生成的列上放置索引,但优化程序不会使用它们。

如果您需要引用单个元素,这些是storing comma-separated lists is a bad idea的原因,即使在JSON字符串中也是如此。

更好的解决方案是使用传统的第三个表来存储多对多数据。每个值都存储在自己的行中,因此您不需要很多列或多个索引。如果需要查找对给定值的引用,可以搜索一列。

select * from table1_table2 where table2_id = 2;