【问题标题】:MySQL - Auto Increment with Prefix as Primary Key on insertMySQL - 插入时以前缀作为主键的自动增量
【发布时间】:2018-08-18 12:41:05
【问题描述】:

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 行的值数不匹配

我在其他线程中查看了解决方案,我发现其中一个需要另一个表进行排序,但我需要在 1 个查询中使用它。

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您可以找到要分配给新记录的当前 auto_increment 值。 并在之前的触发器中使用相同的作为 user_records 表的父用户 ID。 您必须查询 information_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 ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-13
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      相关资源
      最近更新 更多