多次插入并选择到单个查询中

时间:2019-11-19 01:00:18

标签: mysql sql database

有没有一种方法可以将多个插入内容转换为仅单个语句?

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;

2 个答案:

答案 0 :(得分:1)

使用union allunion(取决于您的数据)

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;