简体   繁体   English

创建记录时,Mysql触发器将id从一列复制到同一表中的另一列

[英]Mysql trigger to copy id from one column to another in same table when record is created

I need to copy id field from one column to another when new record is created.创建新记录时,我需要将 id 字段从一列复制到另一列。 Number must be same in both column and in best case it should be inserted in same moment in to the database.两列中的数字必须相同,最好在同一时刻插入到数据库中。 Best solution which i found is probably to use triggers.我发现的最佳解决方案可能是使用触发器。

I created sql like this:我创建了这样的sql:

TRIGGER `db`.`copy_id_into_mbc_id` BEFORE INSERT ON `my_table` FOR EACH ROW
BEGIN
SET NEW.mbc_id = (SELECT AUTO_INCREMENT FROM information_schema.TABLES where TABLE_SCHEMA='mbc' and TABLE_NAME='my_table');
END

This solution seems working but i need to know if it is safe.这个解决方案似乎有效,但我需要知道它是否安全。 I read some old topic as some peoples says it can cause race condition.我读了一些旧话题,因为有些人说它会导致竞争状况。 I'm not sure in which case this is risky as from my test it seems fine.我不确定在哪种情况下这是有风险的,因为从我的测试来看似乎很好。

Is there any better way to be sure that both column have exactly same value when it is inserted?有没有更好的方法来确保两列在插入时具有完全相同的值? Id field is auto incremented and in code i don't know it until record is created but update second field in this moment is to late for me. Id 字段是自动递增的,在代码中我不知道它,直到创建记录,但此时更新第二个字段对我来说为时已晚。

So my question are: With this trigger value in both column will be always same when new record is created?所以我的问题是:创建新记录时,两列中的此触发器值将始终相同? Is there better way to keep both value same in mysql 5.5 or in doctrine/php ?有没有更好的方法可以在 mysql 5.5 或 Dotct/php 中保持两个值相同?

CREATE TABLE test (id INT AUTO_INCREMENT PRIMARY KEY, val INT);
 CREATE TRIGGER tr BEFORE INSERT ON test FOR EACH ROW SET NEW.val = ( SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='test' );
 INSERT INTO test (id) SELECT NULL UNION ALL SELECT NULL; SELECT * FROM test;
\nid |身份证 | val\n-: | -: | --: ——:\n 1 | 1 | 1 1\n 2 | 2 | 1 1\n

db<>fiddle here db<> 在这里摆弄


CREATE TABLE test (id INT AUTO_INCREMENT PRIMARY KEY, val INT);
 CREATE TRIGGER tr BEFORE INSERT ON test FOR EACH ROW SET NEW.val = ( SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='test' );
 CREATE PROCEDURE fill () BEGIN DECLARE cnt INT DEFAULT 0; WHILE cnt < 2 DO INSERT INTO test (id) VALUES (NULL); SET cnt := cnt + 1; END WHILE; END;;
 CALL fill(); SELECT * FROM test;
\nid |身份证 | val\n-: | -: | --: ——:\n 1 | 1 | 1 1\n 2 | 2 | 1 1\n

db<>fiddle here db<> 在这里摆弄

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

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