dsbezji539113152 2014-12-14 07:55
浏览 46
已采纳

MySql db结构按顺序存储项目列表

I need to store and retrieve items of a course plan in sequence. I also need to be able to add or remove items at any point.

The data looks like this:

-- chapter 1
 --- section 1
 ----- lesson a
 ----- lesson b
 ----- drill b
 ...

I need to be able to identify the sequence so that when the student completes lesson a, I know that he needs to move to lesson b. I also need to be able to insert items in the sequence, like say drill a, and of course now the student goes from lesson a to drill a instead of going to lesson b.

I understand relational databases are not intended for sequences. Originally, I thought about using a simple autoincrement column and use that to handle the sequence, but the insert requirement makes it unworkable.

I have seen this question and the first answer is interesting:

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

That way, I would keep adding items in the items table with whatever id and work out the sequence in the sequence table. The only problem with that system is that I need to change the sequence numbers for all items in the sequence table after an insertion. For instance, if I want to insert quiz a before drill a I need to update the sequence numbers.

Not a huge deal but the solutions seems a little overcomplicated. Is there an easier, smarter way to handle this?

  • 写回答

1条回答 默认 最新

  • duanruinong0619 2014-12-14 08:00
    关注

    Just relate records to the parent and use a sequence flag. You will still need to update all the records when you insert in the middle but I can't really think of a simple way around that without leaving yourself space to begin with.

    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
    

    When you need to insert a record in the middle a query like this will work:

    UPDATE items SET sequence=sequence+1 WHERE sequence > 3;
    insert into items (name, parent_id, sequence) values('quiz a', 2, 4);
    

    To select the data in order your query will look like:

    select * from items order by sequence;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 微信实时共享位置修改
    • ¥100 TG的session协议号转成直登号号后客户端登录几分钟后自动退出设备
    • ¥30 共模反馈回路的小信号增益
    • ¥15 arduino ssd1306函数与tone函数放歌代码不兼容问题
    • ¥70 0.96版本hbase的row_key里含有双引号,无法deleteall
    • ¥20 Ida Pro增加插件出现问题
    • ¥15 诊断性META分析合并效能的检验
    • ¥15 请问abb根据色块判断奇偶数并根据批次号放入仓储
    • ¥66 开发PC客户端一定也要开发上位机吗?
    • ¥20 Java eclipse连接数据库