dongpan1308 2015-06-11 09:41
浏览 38
已采纳

MySQL - 使其他列成为自动增量列的函数

This question has been asked but never clearly answered (as far as I am aware): - I want to give my users a unique temporary username. My idea is to make their username a function of the id column as follows: -

id username
  1 user1
  2 user2
  . . . 
  967 user967
  968 user968

I can do this with an INSERT, a SELECT and an UPDATE, but is there a more efficient way? Can it be done with just an INSERT?

  • 写回答

1条回答 默认 最新

  • duanhuan1147 2015-06-11 11:09
    关注

    It can be achieved with a BEFORE INSERT trigger.

    First you need to read current AUTO_INCREMENT value to be assigned and use it to generate the temporary username.

    Example:

    DELIMITER //
    
    DROP TRIGGER IF EXISTS trg_bi_tbl_name //
    
    CREATE TRIGGER trg_bi_tbl_name
           BEFORE INSERT ON tbl_name
           FOR EACH ROW 
    BEGIN
        DECLARE _user_id INT DEFAULT 0;
    
        IF NEW.username IS NOT NULL AND LENGTH( TRIM( NEW.username ) ) = 0 THEN
             SELECT AUTO_INCREMENT INTO _user_id
               FROM INFORMATION_SCHEMA.TABLES
              WHERE TABLE_NAME = 'tbl_name'
                AND TABLE_SCHEMA = DATABASE();
    
             SET NEW.username = CONCAT( 'user', _user_id );
        END IF;
    END;
    
    //
    
    DELIMITER ;
    

    As you mentioned it is for temporary username suggestion, I don't think you need a BEFORE UPDATE trigger.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度