有没有一种方法可以将多个插入内容转换为仅单个语句?
INSERT INTO `subject` (`subject_code`, `student_id`)
SELECT 'mathematics', student_id FROM student;
INSERT INTO `subject` (`subject_code`, `company_id`)
SELECT 'science', student_id FROM student;
INSERT INTO `subject` (`subject_code`, `company_id`)
SELECT 'chemistry', student_id FROM student;
答案 0 :(得分:1)
使用union all
或union
(取决于您的数据)
INSERT INTO `subject` (`subject_code`, `student_id`)
(SELECT 'mathematics' as subjectcode, student_id FROM student
union all
SELECT 'science', student_id FROM student
union all
SELECT 'chemistry', student_id FROM student);
答案 1 :(得分:1)
您也可以使用cross join
进行此操作:
INSERT INTO `subject` (`subject_code`, `student_id`)
SELECT sub.subject, s.student_id
FROM student s CROSS JOIN
(SELECT 'mathematics' as subject UNION ALL
SELECT 'science' as subject UNION ALL
SELECT 'chemistry' as subject
) sub;