mysql向多个表中插入数据

标签 mysql reference insert

我的表是学生、类(class)和学生类(class)。他们之间存在多对多的关系。谁能告诉我为什么下面的代码不起作用?

START TRANSACTION;# MySQL returned an empty result set (i.e. zero rows).
# MySQL returned an empty result set (i.e. zero rows).

INSERT INTO 'students'('StudentID','Fname','Lname')
VALUES (Null,'name','lastname')
# 1 row affected.

SET @student = LAST_INSERT_ID();
# MySQL returned an empty result set (i.e. zero rows).

INSERT INTO `classes`(`classID`, `className`)
VALUES (Null, 'Maths');# 1 row affected.

SET @class = LAST_INSERT_ID();
# MySQL returned an empty result set (i.e. zero rows).

INSERT INTO `studentclasses`(`classID`, `studentID`)
VALUES (@class, @student);
# 1 row affected.

COMMIT;# MySQL returned an empty result set (i.e. zero rows).

最佳答案

START TRANSACTION;

INSERT INTO students(StudentID,Fname,Lname) VALUES (Null,'name','lastname');
SET @student = LAST_INSERT_ID();

INSERT INTO classes(classID, className) VALUES (Null, 'Maths');
SET @class = LAST_INSERT_ID();

INSERT INTO studentclasses(classID, studentID) VALUES(@class, @student);

COMMIT;

它应该可以工作,在新数据库上尝试这个示例 -

CREATE TABLE classes(
  classID INT(11) NOT NULL AUTO_INCREMENT,
  className VARCHAR(20) DEFAULT NULL,
  PRIMARY KEY (classID)
);

CREATE TABLE studentclasses(
  classID INT(11) DEFAULT NULL,
  studentID INT(11) DEFAULT NULL
);

CREATE TABLE students(
  StudentID INT(11) NOT NULL AUTO_INCREMENT,
  Fname VARCHAR(20) DEFAULT NULL,
  Lname VARCHAR(20) DEFAULT NULL,
  PRIMARY KEY (StudentID)
);

START TRANSACTION;

INSERT INTO students(StudentID,Fname,Lname) VALUES (Null,'name','lastname');
SET @student = LAST_INSERT_ID();

INSERT INTO classes(classID, className) VALUES (Null, 'Maths');
SET @class = LAST_INSERT_ID();

INSERT INTO studentclasses(classID, studentID) VALUES(@class, @student);

COMMIT;

SELECT * FROM students;
+-----------+-------+----------+
| StudentID | Fname | Lname    |
+-----------+-------+----------+
|         1 | name  | lastname |
+-----------+-------+----------+

SELECT * FROM classes;
+---------+-----------+
| classID | className |
+---------+-----------+
|       1 | Maths     |
+---------+-----------+

SELECT * FROM studentclasses;
+---------+-----------+
| classID | studentID |
+---------+-----------+
|       1 |         1 |
+---------+-----------+

关于mysql向多个表中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8237951/

相关文章:

php - 选择行 WHERE 参数

python - 如何使用 matplotlib 更新图形

c++ - 标准在哪里定义了将值绑定(bind)到引用的优先顺序?

java - 何时创建变量(内存管理)

python - python 中的 list.insert() 实际上做了什么?

python - 'NoneType' 对象没有属性 'endswith' , django , python

c++ - 返回对 cpp 中数据成员的引用

php - 我的数据库没有插入一些值

optimization - 向 BerkeleyDB-JE 插入数据越来越慢

mysql - 从存储过程更新,但仅当变量不为空时