插入时以前缀作为主键自动递增

tquggr8v  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(254)

MI_TEST_ID | MI_TESTNAME | MI_DATE_CREATED | MI_FLAG | 我试过在插入前触发,但不起作用。插入前是否可以使用触发器自动递增?
mysql中有一个内置的自动增量,但是我希望我的测试id有一个前缀,比如mi001等等。

BEGIN 
INSERT INTO `mi_test` VALUES (NULL);
SET NEW.mi_test_id = CONCAT('MI', LPAD(LAST_INSERT_ID(), 3, '0'))

结束
这是我在phpmyadmin触发器函数中直接使用的触发器。每当我试图插入。它总是说列计数与第1行的值计数不匹配
我在其他线程中查看了解决方案,发现其中一个线程需要另一个表进行排序,但我需要在一个查询中使用它。

gev0vcfq

gev0vcfq1#

您可以找到要分配给新记录的当前自动增量值。并在before触发器中将其用作user\u records表的父用户标识。必须查询schema.tables表中的信息才能找到值。
例子:

use `gknet`;

delimiter $$

drop trigger if exists before_create_user; $$

create definer=`root`@`localhost` trigger `before_create_user` 
       before insert on `users` 
for each row begin
  declare fk_parent_user_id int default 0;

  select auto_increment into fk_parent_user_id
    from information_schema.tables
   where table_name = 'users'
     and table_schema = database();

  insert into user_records ( action, userid, timestamp )
         values ( 'created', fk_parent_user_id, now() );
end;

$$

delimiter ;

相关问题