mysql 同時(shí)向兩張關(guān)聯(lián)表插入數(shù)據(jù)
問題描述
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表增加一條記錄的同時(shí)也要為teacherCourse增加一條記錄,問題是表1的id是自增的,能先獲取剛插入自增的id然后作為表2的teacherId插入數(shù)據(jù)嗎?
問題解答
回答1:1.select (auto_increment-1) from information_scheme.tables where table_name=’TableName’2.select last_insert_id()
回答2:這個(gè)要看你用的數(shù)據(jù)持久層框架了,一般來說都是可以的。mybatis的話你可以看看這些:http://lavasoft.blog.51cto.com/62575/1384959/http://my.oschina.net/u/1256344/blog/159703
hibernate的話也差不多,你搜一下 hibernate/Mybatis 獲取自增id 就可以了。
回答3:Hibernate我用的比較少,平時(shí)用的是Mybatis,說說Mybatis的做法吧。你的teacher表結(jié)構(gòu),id是主鍵,并且自增,是這樣進(jìn)行配置。mybatis xml文件里,需要在insert前面加上
<selectKey resultType='java.lang.Long' order='AFTER' keyProperty='id'> SELECT LAST_INSERT_ID()</selectKey>
即可
回答4:last_insert_id()是一種;觸發(fā)器也可以,
create trigger `insert_teacherCourse` AFTER INSERT on `teacher`for each row insert into teacherCourse(teacherId) values(NEW.id);
大致寫了下,teacherCourse里面還有些是not null的也要插入
相關(guān)文章:
1. 老哥們求助啊2. 我的html頁面一提交,網(wǎng)頁便顯示出了我的php代碼,求問是什么原因?3. html5 - angularjs中外部模版加載無法使用4. tp6表單令牌5. css3 - 請問一下在移動(dòng)端CSS布局布局中通常需要用到哪些元素,屬性?6. npm鏡像站全新上線7. javascript - vue-router怎么不能實(shí)現(xiàn)跳轉(zhuǎn)呢8. python - 模擬滑動(dòng)驗(yàn)證碼,有源碼,求解9. mySql排序,序號10. django - 后臺返回的json數(shù)據(jù)經(jīng)過Base64加密,獲取時(shí)用python如何解密~!
