mysql 同时向两张关联表插入数据
问题描述
create table teacher( id int(11) not null auto_increment, name varchar(10) not null, primary key(id))engine=innodb;create table teacherCourse( teacherId int(11) not null, courseNum int(10) not null, courseName varchar(50) not null, constraint foreign key(teacherId) references staff(id) on delete cascade, primary key(teacherId, courseNum))engine=innodb;
我想在teacher表增加一条记录的同时也要为teacherCourse增加一条记录,问题是表1的id是自增的,能先获取刚插入自增的id然后作为表2的teacherId插入数据吗?
问题解答
回答1:1.select (auto_increment-1) from information_scheme.tables where table_name=’TableName’2.select last_insert_id()
回答2:这个要看你用的数据持久层框架了,一般来说都是可以的。mybatis的话你可以看看这些:http://lavasoft.blog.51cto.com/62575/1384959/http://my.oschina.net/u/1256344/blog/159703
hibernate的话也差不多,你搜一下 hibernate/Mybatis 获取自增id 就可以了。
回答3:Hibernate我用的比较少,平时用的是Mybatis,说说Mybatis的做法吧。你的teacher表结构,id是主键,并且自增,是这样进行配置。mybatis xml文件里,需要在insert前面加上
<selectKey resultType='java.lang.Long' order='AFTER' keyProperty='id'> SELECT LAST_INSERT_ID()</selectKey>
即可
回答4:last_insert_id()是一种;触发器也可以,
create trigger `insert_teacherCourse` AFTER INSERT on `teacher`for each row insert into teacherCourse(teacherId) values(NEW.id);
大致写了下,teacherCourse里面还有些是not null的也要插入
相关文章:
1. nosql - mongodb 多组数据不固定字段查询问题 [百度党请绕道]2. css - 非chrome无法在animation中切换背景图么?3. mysql - 一个sql的问题4. css3 - CSS伪类选择器,如何选择并控制相邻的上一个标签?5. vue.js - linux下怎么使用vue-cli的vue命令6. 微信开放平台 - android 微信支付后点完成按钮,后回调打开第三方页面,屏幕闪动,求解决方法7. css3 - 使用grunt压缩css是能否设置background-size不压缩进去呢?否则ie8不能识别8. javascript - 微信客户端打开的网页,js不运行9. windows-7 - win7下使用cmder,如何设置vim的tab为4个空格?10. pycharm运行python3.6突然出现R6034问题,请问如何处理?
