简体   繁体   English

mySQL和LAST_INSERT_ID问题

[英]mySQL and LAST_INSERT_ID issues

I have a DB-Application and now we have to start with replication (master-master-replication). 我有一个数据库应用程序,现在我们必须从复制开始(master-master-replication)。 We build a stored-function which returns an BIGINT. 我们构建了一个存储函数,该函数返回一个BIGINT。 This value is unique on all involved servers. 此值在所有涉及的服务器上都是唯一的。

The situation: I have a table definition: 情况:我有一个表定义:

create table test (
 id BIGINT not null primary key auto_increment,
 col1 TEXT);

the table has a before insert trigger: 该表具有插入前触发器:

CREATE TRIGGER test_insert BEFORE INSERT ON test
 FOR EACH ROW BEGIN
  IF NEW.id = 0 THEN
   SET @my_uuid = MYUUID();
   SET NEW.id = @my_uuid;
  END IF;
 END;

after an insert into test (col1) values ("foo") I need the value of the LAST_INSERT_ID() - but I only get the value "0". 在插入测试(col1)值(“ foo”)之后,我需要LAST_INSERT_ID()的值-但我只得到值“ 0”。

I tried this in the trigger: 我在触发器中尝试过此操作:

SET NEW.id = LAST_INSERT_ID(@my_uuid);

but it don´t work. 但这不起作用。

I read the mysql manpage which says, that all changes on last_insert_id within triggers and functions will be canceled at the end of the trigger. 我阅读了mysql手册,其中指出,触发器和函数中对last_insert_id的所有更改都将在触发器结束时被取消。

So I try to avoid changing the application (which use php.last_insert_id())... 所以我尽量避免更改应用程序(使用php.last_insert_id())...

any ideas how to solve this without changing php-code? 任何想法如何解决这一问题而无需更改php代码?

greatings. 贺礼。

I assume that you're trying to avoid an insert on the two masters ending up with the same ID. 我假设您正在尝试避免在以相同ID结尾的两个母版上插入。

One way to do this (assuming 2 masters) is to set auto_increment_increment to 2, and auto_increment_offset to 0 on one master, and 1 on the other. 一种方法(假设有2个主机)是将auto_increment_increment设置为2,将一个主机的auto_increment_offset为0,将另一个主机设置为1。

This will result in ids on each master that cannot collide with the other. 这将导致每个主机上的ID不能相互冲突。

Aside: with a bigint and random UUIDs, you current approach is likely to have a collision somewhere around 3 billion rows due to the birthday paradox. 撇开:使用bigint和随机UUID,由于生日悖论,您当前的方法可能会发生约30亿行冲突。

The behavior of LAST_INSERT_ID in mysql in relation to triggers is actually quite "un-standard" when compared to most other database server technologies. 与大多数其他数据库服务器技术相比,mysql中LAST_INSERT_ID与触发器有关的行为实际上是“非标准的”。 But I find it safer and much easier to work with. 但是我发现它更安全,更容易使用。

Anyway, there's no one definite answer to you question, as replication is always complex. 无论如何,对于您的问题,没有一个明确的答案,因为复制总是很复杂。 But the answer of user83591 is sufficient to give you a solution for most cases. 但是user83591的答案足以为您提供大多数情况下的解决方案。 Notion of the birthday paradox is also very much in place. 生日悖论的概念也很到位。 You should accept that as your answer. 您应该接受它作为答案。

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

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