带多个选择语句的插入语句

时间:2020-07-26 05:14:16

标签: sql database postgresql

insert into students_learn_subjects(student_id,subject_id) 
select max(id) from students, subject_id from classes_have_subjects where class_id = 5)

我想在表中插入值,但要从其他表中检索这些值。通过此查询,我收到此错误。第二个选择语句返回多个值,但第一个仅返回一个

ERROR:“ from”处或附近的语法错误

第2行:从学生中选择max(id),从classes_have_s中选择subject_id ...

1 个答案:

答案 0 :(得分:2)

我想这就是你想要的:

INSERT INTO students_learn_subjects (student_id, subject_id) 
SELECT
    (SELECT MAX(id) FROM students),
    subject_id
FROM classes_have_subjects
WHERE class_id = 5;

这假设针对classes_have_subjects表的查询将返回多个记录。根据定义,针对students的max查询必须始终返回单个标量值,因此它可以位于单独的子查询中。