在after insert触发器中,如何获得当期记录的id?用new.id获取不了。why?

解决方案 »

  1.   

    select i_instigate_worker_id into i from tb_owner_apartment_list l where l.i_aprmt_id=new.id and l.e_aprmt_type='apartment' and l.e_rent_or_sale='rent';@@identity和last_insert_id()也试过。
    我需要在after insert的trigger里面获得对应表的新插入记录的id。
      

  2.   

    INSERT BEFORE 触发器中,无法取得auto_increment 的值。 没有办法,因为这个时候数据还没有提交。一种不可靠的变通方法,是取得 max (id) 然后 +1, 但这个风险如下:
    如果有并发进程,也在操作这个表,比如insert ,结果在你得到  max (id) +1 后,提交之前提交了,则造成错误。
    如果有其它程序,删除了最大的记录,也会造成这个ID的重复使用。如果你没有以上问题,则可以使用 max(id) 来实现。
      

  3.   

    如果你用自增,用LAST_INSERT_ID()应该可以,你的代码?
      

  4.   

    用last_insert_id()的风险相同,特别是在session 断开后,或者更新其它表时问题更多。不推荐。