我有这种文本,并希望将其保存到数据库:
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 Table
和Detail Table
,但我必须首先定义Detail Table
的数量。所以,这种文本不可靠。
我的主要问题,如何有效地将这些文本(带有n个孩子)保存到数据库中,并像在示例中一样轻松地显示它?
这是“分层数据”主题。我建议你看看这个伟大的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子句和类似物的很好的答案。