MySQL id 序列
这是 MySQL 中 id 生成的正确方法吗?
插入图片 (图片 ID、First_pick、标题、说明、文件名、Is_Vertical)VALUES
((从图片中选择 max(pictureid)+1),0,?,?,?,?)
我的意思是,当此查询由多个线程运行时,是否能保证 PictureId 是唯一的?
我无法修改表结构。我应该使用任何特定的锁、索引或事务隔离级别吗?
问候, 迈克尔
Is this a correct way for id generation in MySQL ?
INSERT INTO Picture
(PictureId,First_pick,Title,Description,File_Name,Is_Vertical)VALUES
((SELECT max(pictureid)+1 FROM Picture),0,?,?,?,?)
I mean if it is guaranted that PictureId will be unique when this query is run by many threads ?
I can't modify table structure. Should I use any specific locks, index or transaction isolation level ?
Regards, Michal
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您通常会使用
AUTO_INCRMENT
字段来为您处理这些事情:手动不过这个问题还是很好的,我想听听mySQL专家对此的深入回答。按照所描述的方式进行操作有多可靠?
You would usually use an
AUTO_INCREMENT
field that will take care of those things for you: ManualBut the question is good nevertheless, I would like to hear a deep answer from a mySQL expert on this. How reliable would it be to do it in the described way?
除非您充分锁定表(这可能会阻止其他线程访问它而导致问题),否则如果多个线程尝试同时插入记录,您提出的方法将容易受到竞争条件的影响。
Unless you've locked the table adequately - which could cause problems by preventing other threads from accessing it - your proposed approach would be susceptible to race conditions if multiple threads attempt to insert records simultaneously.
如果您确实不能使用 AUTO_INCRMENT 那么您一定应该锁定表以进行写入。
If you really cannot use an AUTO_INCREMENT then you should definitely lock the table for writing.