【发布时间】:2021-02-15 16:16:35
【问题描述】:
考虑以下情况:
我有三个表:Student、StudentCourse、Course。
Student 包含有关学生的信息以及作为主键的唯一 id (uuid)。
Course 包含课程的唯一id(uuid)(主键)和课程的name(文本)。
StudentCourse 通过将courseId (uuid) 与studentId (uuid) 相关联来跟踪学生学习的课程。 courseId 是从 Course 引用 id 的 FK,studentId 是从 Student 引用 id 的 FK。
假设我在Student 中有以下行:
id name
--------------------------
student_id_john John Doe
Course(3 行):
id name
---------------------------
biology_id Biology
mathematics_id Mathematics
physics_id Physics
StudentCourse(1 行):
studentId courseId
----------------------------
student_id_john physics_id
所以目前 John Doe 正在上物理课。
我想更新 StudentCourse 表以反映新的变化:将“物理”课程替换为“数学”课程,并为 John Doe 添加“生物学”课程。
假设我有以下数组(大小可以变化):
let course_arr = ["Mathematics", "Biology"]
我想通过以下方式更新StudentCourse 表:
- 首先从
Course中选择适当的id,其中name= "数学" 和name= "生物学" - 更新现有行(在
StudentCourse中设置courseId=mathematics_id其中studentId=student_id_john - 插入新行:
studentId=student_id_john和courseId=biology_id
有没有办法在一个查询中完成所有这些操作?我只想访问我的数据库一次。我试图避免多次调用数据库。
我尝试了以下查询(将物理课程替换为数学课程),但它不起作用:
update student_course
set "courseId" = subquery.id
from (select id from course where name = 'Mathematics') as subquery
where "studentId" = student_id_john
【问题讨论】:
-
我可能会简单地为该用户删除
student_course中的所有行,然后插入两个(新)课程
标签: arrays postgresql sql-update where-clause