SQL主键自增与时间戳
Premesis:
我知道使用主键的最佳方法是由于索引而将字段设置为整数(是否自动增量),但我处于特殊情况......
我有一个使用 sqlite 作为数据库离线工作的程序(在 PC 和平板电脑上)。 用户可以在程序和中央服务器(如云)之间同步数据。 当用户同步数据时,所有本地更新字段都会在服务器上更新,反之亦然。
在这种情况下使用主键自动增量是一个糟糕的解决方案,因为如果两个用户在表中添加一个字段(在两个不同的设备上),我将复制主键。
然后我添加了另一个包含用户 ID 的字段所以我有一个由以下内容组成的索引: USER_ID
和 FIELD_ID
这样情况就会改变,但仍然可能出现问题...
1)我不能将 FIELD_ID 设置为 AUTO_INCRMENT 2)上述问题仍然存在, 如果用户 Paul 有两个具有相同数据库版本的设备(同时同步),并且在设备 1 中,他在 table_AAA 上执行了一个插入,并且他在 table_AAA 上执行了另一个插入,但从设备 2 中,我将有一个重复的索引( USER_ID / FIELD_ID)
所以我将FIELD_ID转换为由YYYYMMDDHHMMSSmmm组成的varchar(17),这样用户几乎不可能在同一毫秒内进行两次操作。
问题:
在我的情况下有没有更好的方法来设置主键???
Premesis:
I know that the best way to use a primary key is to set the field as integer (autoincrement or not) due to indexes, but I'm in a particular situation...
I have a program that works offline (on both pc and tablet) using sqlite as a database.
The user can sync the datas between the program and the central server (like a cloud).
When the user sync the datas, all the local update field are updated on server and viceversa.
Using a primary key autoincrement in this situation is a bad solution because if two users add a field in a table (on two different device) I'll have the primary key duplicated..
Then I added another field that contains the ID of the user so I have an index formed by:USER_ID
and FIELD_ID
this way the situation change but still there can be problems...
1) I can't have the FIELD_ID as AUTO_INCREMENT
2) The problem described above still remains,
if the User Paul has two device with the same database version (synced at the same time), and in the device 1 he does an insert on table_AAA and he does another insert on table_AAA but from device 2, I will have a duplicate index (USER_ID / FIELD_ID)
So I converted the FIELD_ID as a varchar(17) composed by YYYYMMDDHHMMSSmmm, this way is pretty impossible that an user make two operation at the same millisecond..
The Question:
Is there a better way to set the primary key in my situation???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建第二个独特的字段,即指南。您可以在常规使用时获得快速索引,在合并时获得唯一性。
Create a second, unique field, a guid. You get your fast indexing for regular usage, and uniqness for merging.
您可能应该将 UUID 作为主键,为了更加清晰,您可以添加 device_id 字段来区分行,尽管
UUID
应该足够了。顺便说一下,
UUID
的结果是上升的,也就是说表数据碎片应该不会太困扰你。You should probably have UUID as the primary key, to add more clarity you can add a device_id field to distinguish rows, though
UUID
should suffice.By the way,
UUID
s results ascend, that is table data fragmentation should not bother you much.Long
几乎在每个方面都优于UUID
。我建议您使用Long
类型 pk 使用时间戳值。因此,当设备想要创建对象(离线或在线)时,它会将当前时间戳(以毫秒甚至纳秒为单位)分配给新对象的 pk 值。Long
outperformsUUID
in almost every aspect. I'd suggest you useLong
type pk using timestamp values. So, when a device wants to create an object (either offline or online), it assigns its current timestamp (in milliseconds or even nano) to the pk value of the new object.