从子查询 postgresql 更新列中的所有字段

Update all fields in a column from subquery postgresql

我有一个 table,比如说 buchas,其中包含一个产品列表。我必须创建另一个 table buchas_type,其中的产品类型(class,如果你愿意的话)buchas.

现在我必须通过添加 type_id 列来引用 buchas 中产品的 class。

所以,我的问题可以分为两部分:

我需要一个子查询来根据名称“猜测”产品类型。这应该比较容易,因为产品的名称在某处包含其类型的名称。示例:

   -----------------Name----------------- | ---Type---
               BUCHA GOB 1600                   GOB

问题是我有一个 GOB(2) 类型,它会与 GOB 类型混淆。 (我也有其他类似的类型提出了同样的问题)。

到目前为止,我得到了这个:

SELECT buchas_type.id 
FROM buchas_type 
  JOIN buchas ON buchas.description LIKE '%' || buchas_type.type || '%'
ORDER BY length(type) desc LIMIT 1;

这将解决相似类型的问题,因为它 returns 最长的匹配。但是,我需要一个 WHERE 子句,否则我得到的总是相同的 buchas_type_id。例如,如果我尝试 Where buchas.id = 50,我会得到正确的结果。

问题的第二部分是 UPDATE 命令本身。我需要从我在 (1) 中显示的子查询中填充最近创建的 buchas_type_id。因此,对于 buchas 中的每一行,它必须使用当前行的描述作为参数来搜索 buchas_type 中的类型。

如何实现?

假设您在 buchas 上有一个主键,您的问题的第一部分可以用 distinct on 解决。

select * from buchas;

 buchas_id |    description    | buchas_type_id 
-----------+-------------------+----------------
         1 | BUCHA GOB 1600    |               
         2 | BUCHA GOB(2) 1700 |               
(2 rows)

select * from buchas_type;

 buchas_type_id |  type  
----------------+--------
              1 | GOB
              2 | GOB(2)
(2 rows)

select distinct on (b.buchas_id)  b.buchas_id, t.buchas_type_id, b.description, t.type
  from buchas b 
  join buchas_type t 
    on b.description ilike '%'||t.type||'%' 
 order by b.buchas_id, length(t.type) desc;

 buchas_id | buchas_type_id |    description    |  type  
-----------+----------------+-------------------+--------
         1 |              1 | BUCHA GOB 1600    | GOB
         2 |              2 | BUCHA GOB(2) 1700 | GOB(2)
(2 rows)

解决了这个问题,你可以做一个update...from:

with type_map as (                                              
  select distinct on (b.buchas_id)  b.buchas_id, t.buchas_type_id
    from buchas b 
    join buchas_type t 
      on b.description ilike '%'||t.type||'%' 
   order by b.buchas_id, length(t.type) desc
)
update buchas
   set buchas_type_id = t.buchas_type_id
  from type_map t
 where t.buchas_id = buchas.buchas_id;

UPDATE 2

select * from buchas b join buchas_type t on t.buchas_type_id = b.buchas_type_id;
 buchas_id |    description    | buchas_type_id | buchas_type_id |  type  
-----------+-------------------+----------------+----------------+--------
         1 | BUCHA GOB 1600    |              1 |              1 | GOB
         2 | BUCHA GOB(2) 1700 |              2 |              2 | GOB(2)
(2 rows)