mysql 同时向两张关联表插入数据
高洛峰
高洛峰 2017-04-17 15:14:31
0
4
828
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插入数据吗?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回覆(4)
左手右手慢动作

1.select (auto_increment-1) from information_scheme.tables where table_name='TableName'
2.select last_insert_id()

Peter_Zhu

這個要看你用的資料持久層框架了,一般來說都是可以的。
mybatis的話可以看看這些:
http://lavasoft.blog.51cto.com/62575/1384959/
http://my.oschina.net/u/1256344/blog/159703

hibernate的話也差不多,你搜尋 hibernate/Mybatis 取得自增id 就可以了。

刘奇

Hibernate我用的比較少,平常用的是Mybatis,說說Mybatis的做法吧。
你的teacher表結構,id是主鍵,並且自增,是這樣進行配置。 mybatis xml檔裡,需要在insert前面加上

<selectKey resultType="java.lang.Long" order="AFTER"
            keyProperty="id">
            SELECT LAST_INSERT_ID()
</selectKey>

即可

Peter_Zhu

last_insert_id()是一種;
觸發器也可以,

create trigger `insert_teacherCourse` AFTER INSERT on `teacher`
for each row 
insert into teacherCourse(teacherId) values(NEW.id);

大致寫了下,teacherCourse裡面還有些是not null的也要插入

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!