简体   繁体   English

MySQL程序将数据插入使用auto_increment的表,获取生成的PK auto_increment并将其插入到bridgetable中?

[英]MySQL Procedure to insert data to a table that use auto_increment, get the PK auto_increment generated and insert it into a bridgetable?

I´m creating a restApi with PHP over the courses I have studied.我正在通过我学习的课程使用 PHP 创建一个 restApi。 When it comes to the database I´m not sure whats the best practise for this problem ->当涉及到数据库时,我不确定这个问题的最佳实践是什么 ->

I have data over the languages each course had, to normalize data I have languages in a separate table and a bridge to connect them.我有关于每门课程所用语言的数据,为了规范数据,我在一个单独的表和一个连接它们的桥中拥有语言。

So one table for Courses, one for Languages and one bridge table to connect them.所以一张用于课程的表,一张用于语言的表和一张连接它们的桥接表。

CREATE TABLE `Courses` 
(`Course_ID` INT(11),
`Education_ID` INT(11),
`CourseName` VARCHAR(100) NOT NULL,
`Points` VARCHAR (5),
`Grade` VARCHAR(3), 
PRIMARY KEY (`Course_ID`)
);


CREATE TABLE `Language` (
  `Language_ID` INT(11),
  `Language` VARCHAR(100) NOT NULL,
  `Img_url` VARCHAR (200),
  PRIMARY KEY (`Language_ID`)
);
CREATE TABLE `Bridge_language` (
  `Course_ID` INT(11) NOT NULL,
  `Language_ID` INT(11) NOT NULL,
  KEY `PKFK` (`Course_ID`, `Language_ID`)
);
ALTER TABLE Courses MODIFY Course_ID INTEGER AUTO_INCREMENT;
ALTER TABLE Language MODIFY Language_ID INTEGER AUTO_INCREMENT;

When adding a new course, in the SQL I know the id of the languages, (i will have a function in the admin page where you add new languages) then when you create a new course you just click add languages and the id for the language is added.添加新课程时,在 SQL 中我知道语言的 id,(我将在管理页面中有一个功能,您可以在其中添加新语言)然后当您创建新课程时,您只需单击添加语言和 id添加语言。

But what I don't have is the ID for the course which is created with auto_increment.但是我没有的是使用 auto_increment 创建的课程的 ID。 Is there a smart way you with a function/procedure in SQL, can grab the id that auto_increment has generated and use it to add that into the bridge table?在 SQL 中使用函数/过程是否有一种聪明的方法,可以获取 auto_increment 生成的 id 并将其添加到桥表中?

Or do I need to make a query to the database and grab the latest ID and add one and send that into the bridge table?或者我是否需要查询数据库并获取最新的 ID 并添加一个并将其发送到桥接表中?

In MySQL, you can use last_insert_id() to retrieve the auto-generated id of the last insert query that you executed.在 MySQL 中,您可以使用last_insert_id()来检索您执行的最后一个insert查询的自动生成的 id。 You don't give much details about your code, but the logic is like:您没有提供有关代码的太多详细信息,但逻辑如下:

insert into course (education_id, coursename, points, grade)
values (?, ?, ?, ?);

insert into bridge_language (course_id, language_id)
values (last_insert_id(), ?);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM