我需要按顺序存储和检索类(class)计划的项目。我还需要能够随时添加或删除项目。
数据如下所示:
-- chapter 1
--- section 1
----- lesson a
----- lesson b
----- drill b
...
我需要能够识别顺序,以便当学生完成a 课
时,我知道他需要转到b 课
。我还需要能够在序列中插入项目,例如drill a
,当然现在学生从lesson a
转到drill a
而不是去b 课
。
我了解关系数据库不适用于序列。最初,我想过使用一个简单的自动增量列并用它来处理序列,但插入要求使其行不通。
我见过this question第一个答案很有趣:
items table
item_id | item
1 | section 1
2 | lesson a
3 | lesson b
4 | drill a
sequence table
item_id | sequence
1 | 1
2 | 2
3 | 4
4 | 3
这样,我将继续在 items 表
中添加具有任何 id 的项目,并计算出 sequence 表
中的序列。该系统的唯一问题是我需要在插入后更改序列表中所有项目的序列号。例如,如果我想在drill a
之前插入quiz a
,我需要更新序列号。
没什么大不了的,但解决方案似乎有点过于复杂。有没有更简单、更智能的方法来处理这个问题?
最佳答案
只需将记录与父级相关联并使用序列标志即可。当您在中间插入时,您仍然需要更新所有记录,但我真的想不出一种简单的方法来解决这个问题,而不给自己留下空间。
items table:
id | name | parent_id | sequence
--------------------------------------
1 | chapter 1 | null | 1
2 | section 1 | 1 | 2
3 | lesson a | 2 | 3
4 | lesson b | 2 | 5
5 | drill a | 2 | 4
当您需要在中间插入一条记录时,这样的查询将起作用:
UPDATE items SET sequence=sequence+1 WHERE sequence > 3;
insert into items (name, parent_id, sequence) values('quiz a', 2, 4);
要选择数据,您的查询将如下所示:
select * from items order by sequence;
关于php - MySql 数据库结构按顺序存储项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27467426/