我正在探索使用mysql过程插入嵌入其他json对象的json对象语句的可能性。假设我创建了两个mysql表:
CREATE TABLE `student` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`birth_date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `course` (
`course_id` int(11) unsigned NOT NULL,
`student_id` int(11) unsigned NOT NULL,
`enrollment_date` date NOT NULL,
CONSTRAINT `courses_ibfk_1` FOREIGN KEY (`student_id`) REFERENCES `student` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
假设我正在接收以下json对象,我打算将其转换并插入到student和course表中:
let payload = [
{
name:"Alice",
birth_date:"1968-01-28",
courses:[
{course_id:4325,enrollment_date:"2018-05-01"},
{course_id:3119,enrollment_date:"2018-09-01"},
{course_id:1302,enrollment_date:"2018-01-01"},
],
},
{
name:"Bob",
birth_date:"1971-10-01",
courses:[
{course_id:2000,enrollment_date:"2018-09-01"},
{course_id:3109,enrollment_date:"2018-09-01"},
{course_id:4305,enrollment_date:"2018-09-01"},
],
},
];
在过去,我会使用这样做的客户端代码插入json数据
foreach (payload as student) {
studentId = exec_prepared_statement("INSERT INTO student SET name= ?, birth_date = ?",student.name,student.birth_date)
foreach(student.courses as course){
courseId = exec_prepared_statement("INSERT INTO course SET student_id = ?, course_id = ?, enrollment_date = ?",studentId, course.course_id,course.enrollment_date)
}
}
但我不确定如何使用纯mysql代码实现这一系列插入行为,因为我不确定如何将多维数据传递到mysql存储过程中。如果我能在某处看到这样的例子,那就太好了。
或者,有人可以告诉我,我是否应该完全避免试图通过纯mysql代码插入多维数据……我应该让php、go、js等客户端代码来完成这项工作?我真的很想看看mysql会是什么样子,这样我就可以比较哪一个更易于维护。
暂无答案!
目前还没有任何答案,快来回答吧!