MySQL id 序列

发布于 2024-08-23 20:05:23 字数 271 浏览 9 评论 0原文

这是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

薄暮涼年 2024-08-30 20:05:23

您通常会使用 AUTO_INCRMENT 字段来为您处理这些事情:手动

不过这个问题还是很好的,我想听听mySQL专家对此的深入回答。按照所描述的方式进行操作有多可靠?

You would usually use an AUTO_INCREMENT field that will take care of those things for you: Manual

But 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?

陌路黄昏 2024-08-30 20:05:23

除非您充分锁定表(这可能会阻止其他线程访问它而导致问题),否则如果多个线程尝试同时插入记录,您提出的方法将容易受到竞争条件的影响。

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.

不离久伴 2024-08-30 20:05:23

如果您确实不能使用 AUTO_INCRMENT 那么您一定应该锁定表以进行写入。

If you really cannot use an AUTO_INCREMENT then you should definitely lock the table for writing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文