数据库关系问题
在我的数据库中,我获得了包含 CompanyId 和 Name 列的公司列表。 此外还有用户,这些用户可以添加产品。 表:user 和 user_products 没有定义产品的产品表,它们对于每个用户都是唯一的,因此“user_product”
当用户添加产品时,他键入公司名称。如果该公司名称存在于公司表中,我想建立到公司表的连接,而不是仅将名称保存在 user_product 上。到目前为止一切顺利..我只是将 CompanyId 存储在 user_product 表中。
问题是当用户输入公司表中不存在的名称时。我不想将名称保存为 varchar,而是想在名为 user_company 的表中创建一条新记录。 该表包含以下列:UserCompanyId (PK)、UserId、Name。如果组合 Name 和 UserId 已经存在,我当然不会创建新行,只需引用此 id。
我应该做什么来保持良好的数据库设计。我应该添加这条记录以及 user_product 中一个名为 UserCompanyId 的新列吗?因此,添加新行时始终设置 CompanyId 或 UserCompanyId。感觉这可以通过更好的方式来完成。有人有什么想法吗?
当然,我可以只有一个表“公司”,并且有一列 UserId,当它是系统添加的全球公司时,该列为 null,或者当用户添加了全球不存在的公司名称时,实际上设置了 UserId。这感觉也不太好...
In my database I got a list of companies with columns CompanyId and Name.
Further on there is users and those users can add products.
Tables: user and user_products
There is no product table defining products, they are unique per user therefore "user_product"
When a user adds a product he types a name of a company. If that company name exists in the company table I want to make a connection to the company table instead of saving only the name on the user_product. So far so good.. I just store CompanyId in the user_product table.
The problem is when the user enters a name that doesn't exists in the company table. Instead of saving the name as varchar, I want to create a new record in a table called user_company.
The table got columns: UserCompanyId (PK), UserId, Name. If the combination Name and UserId already exists i will of course not create a new row, just reference to this id.
What should I do to maintain a good database design here.. Should i add this record and also a new column in user_product called UserCompanyId. So that either CompanyId or UserCompanyId is always set when adding a new row. It feels like this could be done in a better way. Anyone got any ideas?
I could of course only have one table "company" and have a column UserId which is null when it's a global company added by the system, or the UserId is actually set when a user has added a company name that didn't existed globally. This doesn't feel good either...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实上,我认为你在最后一段中已经指出了这一点。公司要么由用户定义,要么不是,因此 userId 作为可为空的列是有意义的。这还允许您在公司名称上拥有唯一的键,从而允许您使用数据库来强制公司名称不能重复。
公司表的存在是为了定义公司——哪个用户(或者是否是用户)创建了公司只是关于公司的信息。
Actually, I think you nailed it in your last paragraph. A company is either defined by a user or isn't, so the userId makes sense as a nullable column. This would also allow you to have a unique key on the company name, which allows you to use the database to enforce the fact that a company name can't be duplicated.
Your company table exists to define companies--which user (or whether a user) created the company is just information ABOUT a company.