SQL 复杂更新查询仅过滤不同值

SQL Complex update query filter distinct values only

我有 3 个 table 以下列。

  1. Table:A 列:newColumnTyp1,typ2
  2. Table:B 列:typ2,tableC_id_fk
  3. Table:C 列:id,typ1

我想通过以下逻辑从 C.typ1 更新 A.newColumnTyp1 中的值:

  1. 如果 A.typ2=B.typ2 且 B.tableC_id_fk=C.id
  2. 值必须不同,如果以上任何条件给出多个结果,则应忽略。例如 A.typ2=B.typ2 可能会给出多个结果,在这种情况下应该忽略它。

编辑:

  1. 值必须不同,如果上述任何条件给出多个结果,则只取一个值并忽略其余值。例如 A.typ2=B.typ2 可能会给出多个结果,在这种情况下只需取任何一个值并忽略其余值,因为 A.typ2=B.typ2 的所有结果都将具有相同的 B.tableC_id_fk.

我试过:

SELECT DISTINCT C.typ1, B.typ2
FROM C
  LEFT JOIN B ON C.id = B.tableC_id_fk
  LEFT JOIN A ON B.typ2= A.typ2

它给了我 table 的结果,其中有两列 typ1,typ2 我的逻辑是,然后我将过滤这个新的 table 并将 type2 值与 A.typ2 进行比较并更新 A.newColumnTyp1 我想到了这样的事情但是失败了:

update A set newColumnTyp1= (
SELECT C.typ1 from
SELECT DISTINCT C.typ1, B.typ2
FROM C
  LEFT JOIN B ON C.id = B.tableC_id_fk
  LEFT JOIN A ON B.typ2= A.type2 
where A.typ2=B.typ2);

我正在考虑可更新的 CTE 和 window 功能:

with cte as (
    select a.newColumnTyp1, c.typ1, count(*) over(partition by a.typ2) cnt
    from a
    inner join b on b.type2 = a.typ2
    inner join c on c.id = b.tableC_id_fk
)
update cte
set newColumnTyp1 = typ1
where cnt > 1

更新:如果列具有相同的名称,则为其中之一设置别名:

with cte as (
    select a.typ1, c.typ1 typ1c, count(*) over(partition by a.typ2) cnt
    from a
    inner join b on b.type2 = a.typ2
    inner join c on c.id = b.tableC_id_fk
)
update cte
set typ1 = typ1c
where cnt > 1

我想我会这样处理:

update a
    set newColumnTyp1 = bc.min_typ1
    from (select b.typ2, min(c.typ1) as min_typ1, max(c.typ1) as max_typ1
          from b join
               c
               on b.tableC_id_fk = c.id
          group by b.type2
         ) bc
     where bc.typ2 = a.typ2 and
           bc.min_typ1 = bc.max_typ1;

子查询判断typ1是否始终相同。如果是,则用于更新。

我应该注意到,您可能想要分配最常见的值,而不是要求一致。如果那是你想要的,那么你可以再问一个问题。