MySQL INSERT 和 SELECT 的优先顺序

发布于 2024-09-01 08:26:20 字数 255 浏览 1 评论 0 原文

如果在 mysql 表上同时执行 INSERT 和 SELECT,哪个会先执行?

示例:假设“users”表行数为 0。

然后这两个查询同时运行(假设在同一毫/微秒):

INSERT into users (id) values (1)

最后

SELECT COUNT(*) from users

一个查询会返回 0 还是 1?

if an INSERT and a SELECT are done simultaneously on a mysql table which one will go first?

Example: Suppose "users" table row count is 0.

Then this two queries are run at the same time (assume it's at the same mili/micro second):

INSERT into users (id) values (1)

and

SELECT COUNT(*) from users

Will the last query return 0 or 1?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

晒暮凉 2024-09-08 08:26:20

取决于您的users 表是MyISAM 还是InnoDB。

如果是 MyISAM,一个语句或另一个语句会锁定表,除了 自己锁定表

如果是InnoDB,那就是基于事务的。多版本控制架构允许并发访问表,SELECT 将看到事务开始时的行数。如果同时进行 INSERTSELECT 将看到 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 an INSERT going on simultaneously, the SELECT will see 0 rows. In fact you could even see 0 rows by a SELECT executed some seconds later, if the transaction for the INSERT has not committed yet.

There's no way for the two transactions to start truly simultaneously. Transactions are guaranteed to have some order.

南冥有猫 2024-09-08 08:26:20

这取决于首先执行哪条语句。如果第一个执行,则第二个将返回 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.

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