【发布时间】:2020-11-13 15:49:42
【问题描述】:
表 A 有一个审计表,我需要从中恢复特定列。
行已从表 A 中删除,然后我重新生成它们并通过在特定时间进行匹配(这些是约会记录),我使用以下 SQL 找到了表 A 与其审计表之间的匹配。
select
b_aud.meta,
a.id as a_id,
b.id as b_id
from a
join b on a.id = b.id
join a_aud on
a.course_id = a_aud.course_id and
a.occurrence_start_date_time = a_aud.occurrence_start_date_time and
a.occurrence_end_date_time = saa_audoccurrence_end_date_time and
a.tutor_id = a_aud.tutor_id and
a.student_ids = a_aud.student_ids and
a.term_id = a_aud.term_id
join b_aud on
b_aud.student_id = b.student_id and
b_aud.session_id = a.ac2_session_id
where
a_aud.audit_action = 'DELETE' and
a.occurrence_start_date_time <= current_timestamp and
b_aud.meta::text != '{}'
如您所见,我将返回元数据和受影响行的 ID。我现在需要遍历并更新每个受影响的行并更新元数据,但我正在努力编写一个可以做到这一点的查询。
我尝试过使用 with 子句(report_answers 是上面描述的子查询),但无论我如何编写它,我都会收到多行返回错误。有什么建议吗?
update b b_outer
set meta = (
select report_answers.meta
from report_answers
join a on
a.id = report_answers.a_id
join b on
b.id = report_answers.b_id
where
b_outer.id = report_answers.b_id
)
where
b.id in (
select report_answers.b_id
from report_answers
)
更新是更新表B上的'meta'列 架构:
table A:
pk
occ_start_date_time
occ_end_date_time
student_ids
tutor_id
Term
Table B:
pk
FK to table A
student_id
meta
表 B 中的 1 行对应表 A 中 student_ids 中的每个值。
例如
a:
1 (pk)
'2020-01-01 00:00:00'
'2020-01-01 01:00:00'
[1,2]
1
1
b:
1 (pk)
1 (fk to a)
1(student_id)
{'note': 'something'}
b:
2 (pk)
1 (fk to a)
2 (student_id)
{'note': 'something'}
【问题讨论】:
-
你要更新哪个表A或B,你要更新什么数据?
-
表 b,我可以将架构添加到问题中
-
请添加带有一些示例数据的架构
-
@AkhileshMishra 我添加了架构和示例
-
我已根据您的查询添加了答案
标签: sql postgresql sql-update common-table-expression