使用间接相关数据更新字段

时间:2018-10-01 16:24:50

标签: sql oracle oracle11g

我有四个表:

  • 带有id_studentfirstnamelastname字段的学生表
  • 具有id_studentid_book的租金表
  • 带有id_bookbook_nameauthor_name
  • 的书桌
  • 带有id_bookcurrent_student的预订表

租金表仅具有ID,并且在学生表和书本表之间具有链接。

如何通过预订中的每个booking.current_student用学生表中的firstnamelastname字段(例如'john doe')的串联来更新id_book字段表,从booking.curent_studentstudent.firstname更新student.lastname

由于预订表中没有id_student列,如何从学生表中更新booking.current_student

1 个答案:

答案 0 :(得分:0)

您需要一个相关的更新,该更新使用子查询来获取要在set子句中用于每一行的新值;并且该子查询需要加入租金表和学生表:

update booking b
set current_student = (
  select s.firstname || ' ' || s.lastname
  from rent r
  join student s on s.id_student = r.id_student
  where r.id_book = b.id_book
);

“相关性”部分是子查询在r.id_book = b.id_book上进行过滤,因此它与正在更新的外部bookingb)表相关。

如果booking中有任何行没有匹配的rent行,则将它们设置为null。而且,如果您有多个booking行具有相同的book ID,则它们将全部更新为相同的学生姓名;并且如果您的同一个图书ID有多个rent行,则会出错,因为子查询将返回多行。

复制这样的数据通常不是一个好主意。如果改用视图,则将需要较少的维护:

create view booking (id_book, current_name) as
select r.id_book, s.firstname || ' ' || s.lastname
from rent r
join student s on s.id_student = r.id_student;

然后,当在租金表中添加或删除行时,或者如果学生更改了姓名,视图将自动反映所做的更改,而您无需执行任何操作。