防止两个用户之间的连接多次插入(SQL / SQLite)
我目前正在开发一个项目,我想在 SQLite 数据库中存储两个用户之间的连接和一些附加信息。问题是我想仅存储此连接一次,并且没有此连接的多个条目。
因此,如果我有 userA 和 userB,例如建立此连接的时间(userA、userB、时间),我不希望也能够存储相反的内容(userB、userA、时间)。
我当前的解决方案是对用户进行排序并将它们组合成一个字符串,然后用于创建主键(userAuserB、userA、userB、时间),防止重新插入。但我认为这不是正确的做法。
对于这项任务有更好的解决方案吗?
谢谢,伊普塞隆。
I am currently working on a project where I want to store a connection between two users and some additional information in a SQLite database. The problem is that I want to store this connection exactly once and not have multiple entries for this connection.
So if I have userA and userB and for example the time this connection was made (userA, userB, time), I don't want to be able to store the reverse (userB, userA, time) as well.
My current solution is to sort the users and combine them into a single string, which is then used to create a primary key (userAuserB, userA, userB, time), preventing re-insertion. But I don't think this is the right way to do it.
Is there a better solution for this task?
Thanks, Ypselon.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的 SQLite 版本是 3.31.0+,您可以在表中定义 2 个生成列将是列的最小和最大连接值,然后您可以为它们定义唯一约束:
生成的列是虚拟,这意味着它们不存储在表中。
参见演示。
If your version of SQLite is 3.31.0+ you can define 2 generated columns in the table which will be the min and the max connection values of the columns and then you can define a unique constraint for them:
The generated columns are virtual, meaning that they are not stored in the table.
See the demo.