search

Home  >  Q&A  >  body text

About designing a function that increments a field in mysql.

I have a simple table with three fields, tag_id, user_id, user_tag_id. I want when I insert a record (insert known tag_id and user_id), user_tag_id must be under the condition that user_id = currently inserted user_id self-increment by 1, how to implement this, do I need to write a custom function of mysql?

世界只因有你世界只因有你2706 days ago980

reply all(2)I'll reply

  • 某草草

    某草草2017-06-28 09:25:38

    DELIMITER $$
    DROP TRIGGER IF EXISTS after_insert_table $$
    CREATE TRIGGER after_insert_table
    AFTER INSERT on table
    FOR EACH ROW
    BEGIN
      update table t set t.user_tag_id = t.user_tag_id+1 where t.user_id=new.user_id ;
    END $$
    DELIMITER ;

    reply
    0
  • 欧阳克

    欧阳克2017-06-28 09:25:38

    If only the user_tag_id in the newly inserted record is increased by 1, it can be divided into two sql statements:

    First calculate the maximum value of user_id corresponding to user_tag_id

    select max(user_tag_id) + 1 from t1 where user_id = :user_id

    Then put the return value of the previous statement into the insert statement.

    reply
    0
  • Cancelreply