Postgresql双重交易?

时间:2018-04-10 20:58:43

标签: postgresql postgresql-9.6

我得到了一个包含2个事务的SQL代码示例,一个接一个。这甚至可能吗?如果是这样,哪一个占上风,答案是什么?

要粘贴代码>

    CREATE TABLE cc ( 
  num integer PRIMARY KEY, 
  salary numeric(6,2) DEFAULT 0 
); 

INSERT INTO cc VALUES (1111, 1000.00); 
INSERT INTO cc VALUES (2222, 2000.00);

Session1 BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED; 
Session1 UPDATE cc SET salary = salary - 100.00 WHERE num = 2222; 
    Session2 BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED; 
    Session2 UPDATE cc SET salary = salary + 100.00 WHERE num = 2222; 
Session1 ROLLBACK; 
    Session2 COMMIT;

所以,首先,在PostgreSQL中有可能吗? 2笔交易的逻辑是什么?并且通过示例判断,在ROLLBACK 1st和COMMIT 2nd之后,这是最终薪水吗?

提前谢谢!

1 个答案:

答案 0 :(得分:1)

评论流程:

Session1 BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED; 
Session1 UPDATE cc SET salary = salary - 100.00 WHERE num = 2222; 
-> Session 1 locks row 2222

    Session2 BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED; 
    Session2 UPDATE cc SET salary = salary + 100.00 WHERE num = 2222; 
    -> Session 2 waits for row 2222

Session 1 ROLLBACK; 
-> Session 1 frees row 2222
    -> Session 2 executes UPDATE

    Session 2 COMMIT;
    -> UPDATE 2 is commited

BEGIN TRANSACTION没有锁定任何东西。 UPDATE锁定要修改的行。

了解Transaction IsolationBEGIN.