【问题标题】:How to update a column in a table A using the value from another table B wherein the relationship between tables A & B is 1:N by using max() function如何使用另一个表 B 中的值更新表 A 中的列,其中表 A 和 B 之间的关系是 1:N,使用 max() 函数
【发布时间】:2020-01-07 07:10:03
【问题描述】:

我有两个表,即 loan_detailsloan_his_mapping1:N 关系。我需要通过 loan_his_mapping 表中每个贷款的值来设置 loan_details 表的 hhf_request_id。

由于关系是 1:N ,我想考虑 loan_his_mapping 表中每笔贷款的记录,并具有以下两个条件。表定义如下:

   CREATE TABLE public.loan_details 
 (
       loan_number   bigint NOT NULL,
        hhf_lob     integer,
        hhf_request_id   integer,
        status  character varying(100),
         CONSTRAINT loan_details_pkey PRIMARY KEY (loan_number)
     );


             CREATE TABLE public.loan_his_mapping
          (
               loan_number           bigint NOT NULL,
                spoc_id               integer NOT NULL,
               assigned_datetime     timestamp without time zone,
               loan_spoc_map_id bigint NOT NULL,
                line_of_business_id   integer,
                request_id bigint,
          CONSTRAINT loan_spoc_his_map_id PRIMARY KEY (loan_spoc_map_id),
          CONSTRAINT fk_loan_spoc_loan_number_his FOREIGN KEY (loan_number)
         REFERENCES public.loan_details (loan_number) MATCH SIMPLE
          ON UPDATE NO ACTION ON DELETE NO ACTION );

更新时的加入条件为:

  1. hhf_lob = 4status='Release'的loan_details记录
  2. 我应该考虑使用该记录来更新 loan_his_mapping 表中的“N”条记录中的值,每笔贷款的值为 ma​​x(loan_spoc_map_id)

我现在的查询

 update lsa_loan_details ldet
 set hhf_request_id = history.request_id 
 from loan_his_mapping history  
 where ldet.loan_number = history.loan_number and ldet.status='Release' and  ldet.hhf_lob=4 and 
 history.line_of_business_id=4 ;

我想知道如何使用 loan_his_mappingma​​x(loan_spoc_map_id) 的每笔贷款的记录来更新 loan_details 的列强>表。请帮忙!

【问题讨论】:

  • 您使用的是什么 DBMS?这样的UPDATE 可能在很大程度上依赖于 DBMS。 Edit问题并添加适当的标签。
  • 它的 PostgreSQL 9.6.11
  • 你们清楚我的要求了吗?请帮忙!!

标签: sql postgresql sql-update


【解决方案1】:

你需要一个子查询来获取最高loan_spoc_map_id对应的行

类似的东西:

update loan_details ldet
   set hhf_request_id = history.request_id 
from (
  select distinct on (loan_spoc_map_id) loan_number, request_id
  from loan_his_mapping  lhm
  where lhm.line_of_business_id = 4
  order by loan_spoc_map_id desc
) as history  
where ldet.loan_number = history.loan_number 
  and ldet.status = 'Release' 
  and ldet.hhf_lob = 4;

【讨论】:

  • 非常感谢!!!!!!!根据我的要求更新成功:)
猜你喜欢
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 2021-06-06
  • 2021-06-27
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 2014-05-10
相关资源
最近更新 更多