我有四个表:
id_student
,firstname
和lastname
字段的学生表id_student
和id_book
的租金表id_book
,book_name
,author_name
id_book
,current_student
的预订表租金表仅具有ID,并且在学生表和书本表之间具有链接。
如何通过预订中的每个booking.current_student
用学生表中的firstname
和lastname
字段(例如'john doe')的串联来更新id_book
字段表,从booking.curent_student
和student.firstname
更新student.lastname
。
由于预订表中没有id_student
列,如何从学生表中更新booking.current_student
?
答案 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
上进行过滤,因此它与正在更新的外部booking
(b
)表相关。
如果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;
然后,当在租金表中添加或删除行时,或者如果学生更改了姓名,视图将自动反映所做的更改,而您无需执行任何操作。