如何在 MySQL 中构建列表?
我正在创建一个网站,部分功能是用户可以创建列表。每个用户只能有一个列表,每个列表只能有一个用户。每个列表还有一堆项目。项目可以在多个列表中使用。
假设我有以下表格:
- 用户
- 列表
- 项目
如何定义列表包含哪些项目?现在我正在列表表中存储一串 CSV,但我怀疑这是最好的方法。
谢谢!
I'm creating a website and part of the functionality is that a user can create a list. Each user can only have one list, and each list only has one user. Each list also has a bunch of items. Items can be used in multiple lists.
So let's say I have the following tables:
- Users
- Lists
- Items
How can I define which items a list has? Right now I'm storing a string of CSV's in the Lists table, but I doubt that's the best way.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通常,您的表定义如下:
这样:
请注意,如果您不需要特定于列表的数据(例如名称),则可以完全跳过列表表。
Typically you would have table definitions like:
such that:
Note that you could skip the list table altogether if you didn't need list-specific data like a name.
您需要另一个包含两列的表
Lists_Items
:You'll need another table
Lists_Items
with two columns:我会像这样
用户
构建它
用户 ID(主键)
用户名
ListID(Lists.ListID 的外键)
列表
列表ID(主键)
ListName
ListsToListItems
ListID(Lists.ListID 的外键)
ListItemID(ListItems.ListItemID 的外键)
ListItems
ListItemID(主键)
列表项值
I'd structure it like this
Users
UserID (Primary Key)
UserName
ListID (foreign key to Lists.ListID)
Lists
ListID (Primary Key)
ListName
ListsToListItems
ListID (Foreign Key to Lists.ListID)
ListItemID (Foreign Key to ListItems.ListItemID)
ListItems
ListItemID (Primary Key)
ListItemValue
由于您限制用户只能拥有一个列表(或没有),并且每个列表只属于一个用户,我会这样做:
WIth your restriction that a user can have only one list (or none) and each list belonging to exactly one user, I would do: