downloadTemp2014 2011-03-24 17:22
浏览 38
已采纳

在另一个表中插入时,递增表中的字段

Let's say I have two tables as shown:

user
id    plan     course_limit     username 
10                  0            ahmad

note: plan is enum field containing '','a','b','c'.

course
id    user_id   username
1       10        ahmad

Now I want when a user insert into course as shown I want the course_limit to increment by 1 for that user so that I can apply a limit.

  • 写回答

2条回答 默认 最新

  • dongxian4531 2011-03-24 18:40
    关注

    You can create a trigger with the following code.

    CREATE 
    DEFINER = 'root'@'localhost'
    TRIGGER databasename.AI_course_each
    AFTER INSERT
    ON databasename.course
    FOR EACH ROW
    BEGIN 
    
      UPDATE user SET user.course_limit = user.course_limit + 1
      WHERE user.user_id = new.user_id; 
    
    END;
    

    Some explanation
    You create a trigger that fires once for every row FOR EACH ROW that is inserted AFTER INSERT into table course.

    When you insert into the table you can trigger BEFORE and AFTER the insert is done.
    If you want to be able to prevent the insert you fire before, if you just want to do useful work, you fire after. The inserted fields can be accessed via a dummy table 'new'.

    So here after each insert the UPDATE statement gets executed.

    More trigger options
    You can also use triggers BEFORE UPDATE, AFTER UPDATE,BEFORE DELETE and AFTER DELETE.

    In the update and delete cases you get an extra dummy table old that you can use to refer to the data in the table before the update or delete happened.

    Lots more is possible, but I'll keep it simple for now.

    See http://forge.mysql.com/wiki/Triggers for more info.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导