SQL表-半唯一行?
我有一个基本上具有以下结构的 SQL 表:
PK (int, primary key), userID (int), data (varchar 64)
基本上,由 userID 定义的任何用户都允许存储任意数量的短字符串。但是,不允许任何用户存储两个相同的字符串(尽管用户 1 和用户 2 都可以分别存储相同的字符串)。如果可能的话,我希望在数据库级别实现此限制,因为恕我直言,结构约束应该始终在表中,以及在从表插入/读取数据的程序中。
我唯一能想到的是添加第三列,在其中我在每次插入时连接 userID 和数据,并调用该列唯一,但这对我来说似乎太“hacky”。如果你们中有一个人有更好的方法来做到这一点,我愿意完全重组我的表格,这将允许我在字段上施加这个约束:)
谢谢!
马拉
I have an SQL table with basically the following structure:
PK (int, primary key), userID (int), data (varchar 64)
Basically, any user as defined by userID is allowed to store any number of short strings. However, no user is allowed to store two identical strings (although user 1 and user 2 can both store the same string separately). I would, if at all possible, like to implement this restriction at the database level because IMHO structural constraints should always be in the tables, as well as in the programs inserting/reading data from the tables.
The only thing I can think of is adding a third column in which I concatenate userID and data upon every insert, and call that column unique, but that seems too "hacky" to me. I am open to completely restructuring my tables if one of you guys has a better way of doing this that will allow me to put this constraint on the fields :)
Thanks!
Mala
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
听起来您需要对 userID 和数据列进行复合唯一约束。
像这样:
Sounds like you need a composite unique constraint on the userID and data columns.
like this:
如果我们对 UserId 和 Data 有唯一约束怎么办?我希望它能解决您的问题。
What if we have a unique constraint on UserId and Data. I hope it should solve your issue.
您需要一个复合键,可以将其添加到 MySQL 中的表
tablename
中:You want a composite key, which you can add to your table
tablename
like this in MySQL:我认为最简单的解决方案是创建一个索引,
尽管这可能会产生开销。
这种看起来也应该是您的主键,尽管这实际上取决于 PK 和 userId 在整个模式的其余部分中的表中所扮演的角色。
I think the simplest solution would be to create an index
though there may be an overhead with this.
This kind of looks like it should be your primary key as well, though that really depends on the role PK and userId play in tables throughout the rest of the schema.
我认为组合键可以完成这项任务。使用 UserId 和数据列创建复合键。在这种情况下,当用户尝试多次插入相同的数据时,它将抛出错误,您可以在应用程序中捕获该错误并向用户显示适当的错误消息。
希望它有帮助...
谢谢。
I think a composite key will do the task. Create a composite key with UserId and data columns. In this case, when a user tries to insert same data morethan once, it will throw error, which you can catch in your application and show the user an appropriate error message.
Hope it helps...
Thanks.