我如何锁定 MySQL 或 phpmyadmin 中的表?
我需要使用一张桌子作为排队系统。该表将不断更新。
例如,我的网站上的多个用户将添加他们的文件进行处理,我听说当多个用户同时发生更新时,表格会变得无响应或类似的情况。
那么在这种情况下我需要锁定表吗?如何对 mysql 表应用锁?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不断更新是指每秒会追加10,000次吗?即使对于中端服务器,每秒仍然有 10,000 个机会让其他用户共享该表。
仅当多个相关操作需要作为一个单元发生时才需要锁定表。在大多数情况下,将一系列操作包含在数据库事务中就足够了。如果“不断更新”仅仅是
插入一些表值(...)
,那么就很容易保证事务一致性。By constantly be updated do you mean it will be appended to 10,000 times per second? Even for middle-range servers, that still presents 10,000 opportunities per second for the table to be shared by other users.
It's only necessary to lock the table when several dependent operations need to occur as a unit. In most cases, it is sufficient to include the series of operations in a database transaction. If the "constant updates" are merely
insert sometable values ( ...)
, then it will be easy to guarantee transaction consistency.所有表都可以锁定,没有特殊类型的表。也就是说,当遇到僵局时处理这个问题。 隔离级别也是一个密切相关的主题。
有 锁定表语法 - 本文介绍了如何&为什么你想要锁定表。
All tables can be locked, there isn't a special type of table. That said, deal with the issue when you run into deadlocks. Isolation levels are a closely related topic as well.
There's the LOCK TABLES syntax - this article covers how & why you'd want to lock tables.
当您一次执行多个更新时,可能会陷入死锁情况。 InnoDB 等引擎将检测到这一点并导致您的一个事务失败(您可以重试,但只能重试整个事务)。
您可以通过表锁定来避免这种情况,但它会降低并发性。
像 MyISAM 这样的引擎(无论如何都不支持 MVCC 或事务)无论如何都会隐式使用表锁定。此类表锁仅在查询期间存在;在不再需要该表后,它们会很快自动释放(不一定尽快,但很快)。
我建议您不要使用 LOCK TABLE,除非您觉得确实需要;如果遇到死锁,请重试事务。
When you do several updates at once, you can get into a deadlock situation. Engines such as InnoDB will detect this and fail one of your transactions (You can retry, but only the whole transaction).
You can avoid this by table locking, but it reduces concurrency.
Engines such as MyISAM (which does not support MVCC or transactions anyway) use table locking implicitly anyway. Such table locks exist only for the duration of a query; they're automatically released soonish after the table isn't needed any more (not necessarily as soon as possible, but quite soon)
I recommend you do not use LOCK TABLE unless you feel you really need to; if you get a deadlock, retry the transaction.