防止两个用户之间的连接多次插入(SQL / SQLite)

发布于 2025-01-09 00:07:44 字数 298 浏览 5 评论 0原文

我目前正在开发一个项目,我想在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

意中人 2025-01-16 00:07:44

如果您的 SQLite 版本是 3.31.0+,您可以在表中定义 2 个生成列将是列的最小和最大连接值,然后您可以为它们定义唯一约束:

CREATE TABLE tablename (
  userA TEXT,
  userB TEXT,
  user1 GENERATED AS (MIN(userA, userB)),
  user2 GENERATED AS (MAX(userA, userB)),
  UNIQUE(user1, user2)
);

生成的列是虚拟,这意味着它们不存储在表中。

参见演示

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:

CREATE TABLE tablename (
  userA TEXT,
  userB TEXT,
  user1 GENERATED AS (MIN(userA, userB)),
  user2 GENERATED AS (MAX(userA, userB)),
  UNIQUE(user1, user2)
);

The generated columns are virtual, meaning that they are not stored in the table.

See the demo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文