简体   繁体   English

MySQL事务和触发器

[英]MySQL transaction and triggers

Hey guys, here is one I am not able to figure out. 大家好,我不知道这是哪一个。 We have a table in database, where PHP inserts records. 我们在数据库中有一个表,其中PHP插入记录。 I created a trigger to compute a value to be inserted as well. 我创建了一个触发器来计算要插入的值。 The computed value should be unique. 计算值应该是唯一的。 However it happens from time to time that I have exact same number for few rows in the table. 但是,有时会发生表格中几行的完全相同的数字。 The number is combination of year, month and day and a number of the order for that day. 该数字是年,月和日的组合以及当天的订单数量。 I thought that single operation of insert is atomic and table is locked while transaction is in progress. 我认为插入的单个操作是原子的,并且在进行事务时表被锁定。 I need the computed value to be unique...The server is version 5.0.88. 我需要计算出的值是唯一的...服务器是5.0.88版。 Server is Linux CentOS 5 with dual core processor. 服务器是带有双核处理器的Linux CentOS 5。

Here is the trigger: 这是触发器:

CREATE TRIGGER bi_order_data BEFORE INSERT ON order_data
FOR EACH ROW BEGIN
  SET NEW.auth_code = get_auth_code();
END;

Corresponding routine looks like this: 相应的例程如下所示:

CREATE FUNCTION `get_auth_code`() RETURNS bigint(20)
BEGIN
    DECLARE my_auth_code, acode BIGINT;
    SELECT MAX(d.auth_code) INTO my_auth_code
        FROM orders_data d
        JOIN orders o ON (o.order_id = d.order_id)
        WHERE DATE(NOW()) = DATE(o.date);

    IF my_auth_code IS NULL THEN
        SET acode = ((DATE_FORMAT(NOW(), "%y%m%d")) + 100000) * 10000 + 1;
    ELSE
        SET acode = my_auth_code + 1;
    END IF;
    RETURN acode;
END

I thought that single operation of insert is atomic and table is locked while transaction is in progress 我以为插入的单个操作是原子的,并且在进行事务时表被锁定

Either table is locked (MyISAM is used) or records may be locked (InnoDB is used), not both. 要么表被锁定(使用MyISAM),要么记录被锁定(使用InnoDB),但不能两者都被锁定。

Since you mentioned "transaction", I assume that InnoDB is in use. 既然你提到了“事务”,我认为InnoDB正在使用中。 One of InnoDB advantages is absence of table locks, so nothing will prevent many triggers' bodies to be executed simultaneously and produce the same result. InnoDB的优点之一是没有表锁,因此没有什么可以阻止许多触发器的主体同时执行并产生相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM