MySQL 中的 AUTO_INCRMENT 作用域?
我在 Rails 应用程序中使用 MySQL。我有一个用户表(标准内容,如 id、名称等)和一个书籍表(同样包含 id、user_id 和 title 等)。
我想要一个列(我们称之为 user_book_id),它应该像 id 一样自动递增,但范围是 user_id 。就像id一样,即使在books表中删除了一条记录,user_book_id也不应该被重复使用。一个例子:
User
id | Name
------------
1 | Jerry
2 | Newman
Book
id | user_id | user_book_id | Title
-----------------------------------
1 | 1 | 1 | Jerry's First Book
2 | 1 | 2 | Jerry's Second Book
3 | 2 | 1 | Newman's First Book
4 | 1 | 3 | Jerry's Third Book
有没有办法在 MySQL 中做到这一点?我进行了搜索,但没有找到任何东西。
谢谢, 普拉泰克
I am using MySQL in a rails application. I have a users table (standard stuff like id, name etc) and a books table (again with id, user_id and title etc).
I would like to have a column (lets call it user_book_id) that should be auto incremented like id but scoped with user_id. Just like id, even if a record is deleted in the books table, the user_book_id should not be reused. An example:
User
id | Name
------------
1 | Jerry
2 | Newman
Book
id | user_id | user_book_id | Title
-----------------------------------
1 | 1 | 1 | Jerry's First Book
2 | 1 | 2 | Jerry's Second Book
3 | 2 | 1 | Newman's First Book
4 | 1 | 3 | Jerry's Third Book
Is there a way to do this in MySQL? I searched but could not find anything.
Thanks,
Prateek
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不存在这样的事情。要么允许 auto_increment 在整个表中是唯一的,要么您必须自己实现它。
No, no such thing exists. Either allow the auto_increment to be unique across the table, or you have to implement it yourself.
您可以自己实现它,假设您将最后一个 user_book_id 值放入 users 表中的新列中,然后在插入 books 时,从 users 中的新列中取出值并递增 +1。
You can implement it by yourself, lets say if you put the last user_book_id value in a new column in the users table, then when inserting in books, take the value from the new column in users and increment +1.