如何设计数据库(SQL或非SQL(来有效地存储每个项目的顺序/位置?我试着用不同的措辞来搜索我的问题,但没有成功,希望有人能在这里帮助我。
想象一个待办事项列表,您可以在其中创建/删除任务,并(通过拖动(将其重新排序到任何位置。
简单地说,你是唯一的用户,所以不要担心userId
你可以有数百万个任务,什么是有效的设计来存储这个位置/订单?
我能想到的最好的方法是为这个职位提供一个大数字:
task_id | 位置 |
---|---|
任务1 | 10000 |
任务2 | 20000 |
任务3 | 300000 |
如果只有整数。您可以在大约两个查询中执行此操作。
#
# Take the current position of the element and the desired position element
# Then add the base increment(1 in your case 100000) to all the position
# between desired and current position
#
UPDATE tasks
SET
position = position + 100000
WHERE
position >= 200000 AND position <= 400000;
# Now update your task to the desired value
UPDATE tasks
SET
position = 200000
WHERE
task_id = 4;
这将更新你的所有职位,使其拥有你想要的所需职位。我还没有对它进行基准测试,但这应该可以很好地用于大约10万的数据。