国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

mysql 同時向兩張關聯表插入數據

瀏覽:123日期:2022-06-20 09:09:40

問題描述

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的也要插入

相關文章:
主站蜘蛛池模板: 永胜县| 广东省| 宁安市| 莱芜市| 万山特区| 江北区| 呼图壁县| 民乐县| 应用必备| 东莞市| 广元市| 唐山市| 永吉县| 亳州市| 彭阳县| 平和县| 陆丰市| 福安市| 万源市| 聊城市| 浑源县| 靖江市| 宜阳县| 马边| 鹤峰县| 屏东市| 甘肃省| 犍为县| 高雄市| 承德县| 长春市| 西丰县| 克东县| 阜康市| 贵南县| 锡林郭勒盟| 新竹县| 呼图壁县| 沂水县| 巫山县| 华阴市|