如何有效地将动态文本保存到数据库中?

时间:2019-04-30 03:12:14

标签: mysql database-design

我有这种文本,想将其保存到数据库中

I. Master Text I                                            <<<Parent
   I.A. Sub Master Text I                                   <<<Child
      I.A.1.  Sub Sub Master Text I                         <<<Child Child                    
         I.A.1.a Sub Sub Sub Master Text I - Row 1          <<<Child Child Child 1
         I.A.1.b Sub Sub Sub Master Text I - Row 2          <<<Child Child Child 2
         I.A.1.c Sub Sub Sub Master Text I - Row 3          <<<Child Child Child 3

II. Master Text II
   II.A. Sub Master Text II
      II.A.1.  Sub Sub Master Text II
         II.A.1.a Sub Sub Sub Master Text II - Row 1
      II.A.2.  Sub Sub Master Text II
         II.A.2.a Sub Sub Sub Master Text II - Row 1
         II.A.2.b Sub Sub Sub Master Text II - Row 2

III. Master Text III
   III.A. Sub Master Text III
      III.A.1.  Sub Sub Master Text III
         III.A.1.a Sub Sub Sub Master Text III - Row 1
         III.A.1.b Sub Sub Sub Master Text III - Row 2
         III.A.1.c Sub Sub Sub Master Text III - Row 3
   III.B. Sub Master Text III

如何有效保存这些文本?总有一个Parent,但是Child的数量是动态的。我无法预测会有多少child存在。

我目前使用常规的Master TableDetail Table,但必须首先定义Detail Table的编号。因此,这种文本不可靠。

我的主要问题,如何有效地将这些文本(带有n个孩子)保存到数据库中,并像示例中那样轻松地显示它?

1 个答案:

答案 0 :(得分:1)

这是“分层数据”主题。 我建议您看看这个很棒的presentation,然后为您选择最佳的方式。

但是,MySql 8支持递归with子句,因此您可以使用如下代码:

CREATE TABLE `texts` (
  `id` INT NOT NULL,
  `text` TEXT NULL,
  `parent_id` INT NULL,
  PRIMARY KEY (`id`));

以及选择遵循第一棵树的子项目的示例:

with recursive cte (id, text, parent_id) as (
  select     id,
             text,
             parent_id
  from       texts
  where      parent_id = 1
  union all
  select     p.id,
             p.text,
             p.parent_id
  from       texts p
  inner join cte
          on p.parent_id = cte.id
)
select * from cte;

Here,对于旧版本的with子句和类似物,您可以找到很好的答案。