最近以前的同事问到两个表如何共用一个自增id想了下 用触发器比较好实现。
创建3个表
test ,test1 ,test2
其中 都只有一个主键 id ,其中test 表id 为自增
test1 上创建触发器
DROP TRIGGER IF EXISTS `t`//
CREATE TRIGGER `t` BEFORE INSERT ON `test1`
FOR EACH ROW BEGIN
declare testid int;
insert into test values (null);
select id into @testid from test order by id desc limit 1;
set new.id = @testid;
END
//
test2 表上创建同样的触发器
这样两个表就共用了 test 表的自增id .