douqian2334 2015-02-01 19:25
浏览 92

PHP MySQLi插入获取最后一列值加1

I'm trying to run an INSERT query into a table with 3 columns. The first column is where I'm having the issue.

It is called COMM_CODE with VARCHAR value of 10 length, and is the primary key, ALLOW NULL is unchecked.

The values for COMM_CODE look like this:

 COMM_CODE
 c20188
 c20189
 c20190
 // and so on

What I would like to do, is when a new record is inserted, to basically add 1 to the most recent record.

Therefore, the most recent record is:

 c20190

So when I add a new record, the COMM_CODE for the new record will be:

 c20191

I tried this:

 INSERT INTO table_c 
   (COMM_CODE, COMM_DESC, DATE) 
 VALUES 
   (''+1, 'VIDEO GAMES', NOW());

But that just adds a number 1 to that column.

How can I make this happen?

  • 写回答

1条回答 默认 最新

  • duanlongnao0028 2015-02-01 21:06
    关注

    Here the solution for your query : To generate the new code I'hv created get_new_code function in mysql. I hope you know how funcions work in mysql.

    CREATE FUNCTION `get_new_code`() RETURNS varchar(11)
    BEGIN 
        Declare var_code VARCHAR(11);
        SELECT max(`COMM_CODE`) INTO var_code FROM table_c;
        RETURN (CONCAT('c',(convert(substr(var_code,2,length(var_code)), SIGNED INTEGER)+1)));
    END
    

    Just to verify your logic you can use :

    select get_new_code();
    

    So that you will get the clear picture. Call this get_new_code function in insert query like this :

    INSERT INTO 
    `table_c`(`COMM_CODE`, `COMM_DESC`, `COMM_DATE`) 
    VALUES 
    (get_new_code(),'Description text',NOW());
    

    This should solve your problem. :)

    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数