如何为一组具有不同密钥的记录生成uniqueidentifier?

zc0qhyus  于 2021-08-13  发布在  Java
关注(0)|答案(3)|浏览(361)

我有一个这样的记录集:

| key_sk | unique_id                            |
|--------|--------------------------------------|
| 2      | null                                 |
| 2      | null                                 |
| 3      | 83a1c90b-e58d-4db4-b438-a79edfb28e60 |
| 3      | 83a1c90b-e58d-4db4-b438-a79edfb28e60 |
| 4      | 4ce66783-0b84-4e8a-a0de-c3284e4d9cd0 |
| 5      | null                                 |

我想为每个唯一的 key_sk 设置 unique_id 为空。以上我想 key_sk 2 单身 unique_id 就像 key_sk 3 做。
我下面的尝试产生了不同的结果 uniqueidentifier 每一套。我认为这是因为公共表表达式的递归性质:每个连接到cte都会导致 NEWID() 被称为。

;with update_id_cte as
(
  select distinct hr.key_sk
        ,NEWID() as gened_unique_id
    from history_record hr
   where hr.unique_id is null
)
update hr
   set hr.unique_id = cte.gened_unique_id
  from history_record hr
       join update_id_cte cte
         on hr.key_sk = cte.key_sk

可能有一种比使用cte更简单的方法来实现这一点。如何生成和更新 history_record 单张table uniqueidentifier 对于每个不同的 key_sk ?

uqxowvwt

uqxowvwt1#

至少在mysql的旧版本中,这可能是一个麻烦,因为您正在检查并希望检查同一列,一种方法是使用临时表。
这不是一个查询,而是存储过程的一部分,但如果只执行一次,就可以运行它。

CREATE TEMPORARY TABLE IF NOT EXISTS tmp
select distinct hr.key_sk ,NEWID() as gened_unique_id
from history_record hr
where hr.unique_id is null;

update hr
set hr.unique_id = tmp.gened_unique_id
from history_record hr
inner join tmp on hr.key_sk = tmp.key_sk;
guykilcj

guykilcj2#

我认为,如果您首先选择distinct,它应该像您期望的那样工作 key_sk 在子查询中,然后分配一个新id newid() 每个不同的目标只调用一次 key_sk :

with update_id_cte as (
    select key_sk, newid() as gened_unique_id
    from (select distinct key_sk from history_record where unique_id is null) t
)
update hr
set hr.unique_id = cte.gened_unique_id
from history_record hr
inner join update_id_cte cte on hr.key_sk = cte.key_sk
dgiusagp

dgiusagp3#

而不是 select distinct ,您可以使用 group by :

with update_id_cte as (
       select hr.key_sk, NEWID() as gened_unique_id
       from history_record hr
       where hr.unique_id is null
       group by hr.key_sk
      )
update hr
   set hr.unique_id = cte.gened_unique_id
   from history_record hr join
        update_id_cte cte
        on hr.key_sk = cte.key_sk;

如果有可能 key_sk 价值观两者兼有 NULL 而不是- NULL 如果要保留现有值,可以调整逻辑:

with update_id_cte as (
       select hr.key_sk, coalesce(max(hr.unique_id), NEWID()) as gened_unique_id
       from history_record hr
       group by hr.key_sk
      )
update hr
   set hr.unique_id = cte.gened_unique_id
   from history_record hr join
        update_id_cte cte
        on hr.key_sk = cte.key_sk
   where hr.unique_id is null;

相关问题