MySQL INSERT 和 SELECT 的优先顺序
如果在 mysql 表上同时执行 INSERT 和 SELECT,哪个会先执行?
示例:假设“users”表行数为 0。
然后这两个查询同时运行(假设在同一毫/微秒):
INSERT into users (id) values (1)
最后
SELECT COUNT(*) from users
一个查询会返回 0 还是 1?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
取决于您的
users
表是MyISAM 还是InnoDB。如果是 MyISAM,一个语句或另一个语句会锁定表,除了 自己锁定表。
如果是InnoDB,那就是基于事务的。多版本控制架构允许并发访问表,
SELECT
将看到事务开始时的行数。如果同时进行INSERT
,SELECT
将看到 0 行。事实上,如果INSERT
的事务尚未提交,您甚至可以在几秒钟后执行SELECT
看到 0 行。两个事务不可能真正同时开始。交易保证有一定的顺序。
Depends whether your
users
table is MyISAM or InnoDB.If it's MyISAM, one statement or the other takes a lock on the table, and there's little you can do to control that, short of locking tables yourself.
If it's InnoDB, it's transaction-based. The multi-versioning architecture allows concurrent access to the table, and the
SELECT
will see the count of rows as of the instant its transaction started. If there's anINSERT
going on simultaneously, theSELECT
will see 0 rows. In fact you could even see 0 rows by aSELECT
executed some seconds later, if the transaction for theINSERT
has not committed yet.There's no way for the two transactions to start truly simultaneously. Transactions are guaranteed to have some order.
这取决于首先执行哪条语句。如果第一个执行,则第二个将返回 1,如果第二个先执行,则它将返回 0。即使您在具有多个物理核心的计算机上执行它们,并且由于锁定机制,它们也永远不会以完全相同的速度执行时间戳。
It depends on which statement will be executed first. If first then the second will return 1, if the second one executes first, then it will return 0. Even you are executing them on the computer with multiple physical cores and due to the lock mechanism, they will never ever execute at the exactly same time stamp.