用户和组之间有多对多关系:组可能包含很少的用户并包含多个组。 服务器向我发送这样的json,我需要将其存储到DB:
group: {
name: "test", id: "UUID"
users: [
{name: "user1", id: "UUID"},
{name: "user2", id: "UUID"},
{name: "user3", id: "UUID"}
]
}
问题是:用户在组中的顺序很重要 - 用户应该以与服务器 json 中相同的顺序显示。 我使用的第一个解决方案是添加到组字段,例如
user_ids: [user1_uuid, user2_uuid, user3_uuid]
并将其以json格式存储到数据库中,但我在这个解决方案中看到两个问题:
SELECT * FROM user WHERE id IN (:user_ids)
如何存入DB和SELECT?
在 SQL 中,表行确实是无序的;获得有序行的唯一有保证的方法是使用 ORDER BY。
如果数组元素的顺序很重要,请为数组索引添加一列。
您可以使用以下架构:
CREATE TABLE user(id integer primary key, name text);
CREATE TABLE grp(id integer primary key, name text);
CREATE TABLE usergrp(userid integer, grpid integer, position integer);
CREATE INDEX positionindex on usergrp(grpid, position);
然后您可以使用查询检索属于某个组的用户
SELECT userid FROM usergrp WHERE grpid=? ORDER BY position;
另外,也许您想为 usergrp 使用 “无 rowid” sqlite 表存储选项。