SQLITE 中列中的任意数量的条目

发布于 2024-11-02 06:53:23 字数 205 浏览 1 评论 0原文

自从我使用 SQL 以来已经有一段时间了,我在为数据库中的表找到最佳模式时遇到了困难。

最终,我有一群用户(主键),每个用户都有许多我正在跟踪的属性。其中一个属性是它们所属的一组组(想想博客文章具有标签的方式 - 多个帖子可以共享相同的标签,并且相同的标签可以有多个帖子)。

为该数据库构建表的最佳方法是什么,以便我可以轻松检查与用户关联的组以及属于给定组的用户?

It's been a while since I used SQL, and I'm having trouble coming up with the best schema for the table(s) in my database.

Ultimately, I have a bunch users (primary key) which each have a number of attributes that I'm keeping track of. One of these attributes is a set of groups to which they belong (think of the way blog posts have tags - multiple posts can share the same tag, and the same tag can have multiple posts).

What is the best way to construct the table(s) for this database so that I can easily check the groups associated with a user, and also the users who belong to a given group?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

浅笑依然 2024-11-09 06:53:23

通常,每列只有 0 或 1 个条目,不能再多了。 (可以说,Null 是一个条目,因此从这个意义上说,每列实际上始终有 1 个条目)。当您考虑在一列中包含多个条目时,就需要分解模型了。

从基本数据元素开始,忘记它们如何相互关联:

User
-----
ID
Name
Group
----------
ID
Description

然后将两者链接起来:

UserGroup
----------
UserID
GroupID

用户可能拥有的其他“单一”属性(电子邮件地址、URL、年龄等)将放入用户表中。

例子:

User: ID = 1, Name = John
User: ID = 2, Name = Mary
Group: ID = 1, Description = Boys
Group: ID = 2, Description = Students
Group: ID = 3, Description = Programmers
UserGroup: UserID = 1, GroupID = 1  -> John is a member of "Boys"
UserGroup: UserID = 1, GroupID = 2  -> John is also a member of "Students"
UserGroup: UserID = 2, GroupID = 2  -> Mary is another member of "Students"

As a rule, there's only 0 or 1 entry per column, no more. (Arguably, Null is an entry, so in that sense there really is always 1 entry per column). When you're thinking of having several entries in a column, it's time to break down the model.

Start with your basic data elements, forget about how they relate with each other:

User
-----
ID
Name
Group
----------
ID
Description

Then link the two:

UserGroup
----------
UserID
GroupID

The other "single" attributes that the user could have (e-mail address, url, age, whatever) would go in the User table.

Example:

User: ID = 1, Name = John
User: ID = 2, Name = Mary
Group: ID = 1, Description = Boys
Group: ID = 2, Description = Students
Group: ID = 3, Description = Programmers
UserGroup: UserID = 1, GroupID = 1  -> John is a member of "Boys"
UserGroup: UserID = 1, GroupID = 2  -> John is also a member of "Students"
UserGroup: UserID = 2, GroupID = 2  -> Mary is another member of "Students"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文