mysql 原子操作,是在MySQL上插入/更新一个原子操作吗?

In a Mysql database with every table based on InnoDB with Autocommit enabled, will queries with subqueries and/or joins be atomic?

Examples:

INSERT INTO users SELECT (x,y,z) FROM users, comments WHERE users.id = comments.user_id; (joins)

UPDATE users, comments SET users.x = x1 WHERE users.age > 30; (joins)

UPDATE users, comments SET users.x = x1, comments.y = y1 WHERE users.age > 30; (joins)

UPDATE users, comments SET users.x = x1, comments.y = y1 WHERE users.id IN (SELECT id FROM users WHERE age > 30); (subqueries)

解决方案

I understand your question like "is each of those queries in itself an atomic operation?". Then the answer is "yes".The other two answers are right, when they say that all your statements together are not atomic.

Atomicity in databases only means all or nothing. It does not mean correctness of data. Your statement succeeds or not. It has nothing to do with joins or subqueries. One statement is one statement, no matter if your database has to use a temporary table in memory or on disk or not.

Transactions just tell your database to treat multiple statements as one statement. When one of the statements fails, all of them are rolled back.

An important related topic here is the isolation level. You might want to read up about those.

EDIT (to answer the comment):

That's right. As long as it is a valid statement and no power failure occurs or other reasons why a query could fail, it's being done. Atomicity in itself just guarantees that the statement(s) is/are being done or not. It guarantees completeness and that data is not corrupt (cause a write operation didn't finish or something). It does not guarantee you the correctness of data. Given a query like INSERT INTO foo SELECT MAX(id) + 1 FROM bar; you have to make sure via setting the correct isolation level, that you don't get phantom reads or anything.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值