gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:48:10 36 4
gpt4 key购买 nike

我有带有 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 对。但是在这种情况下如何使用索引呢?

最佳答案

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

我认为观点与这个问题无关。

您可以使用 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;

关于mysql - mysql中如何组织Json存储多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49630639/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com