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

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

我有一个这样的记录集:

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

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

  1. ;with update_id_cte as
  2. (
  3. select distinct hr.key_sk
  4. ,NEWID() as gened_unique_id
  5. from history_record hr
  6. where hr.unique_id is null
  7. )
  8. update hr
  9. set hr.unique_id = cte.gened_unique_id
  10. from history_record hr
  11. join update_id_cte cte
  12. on hr.key_sk = cte.key_sk

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

uqxowvwt

uqxowvwt1#

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

  1. CREATE TEMPORARY TABLE IF NOT EXISTS tmp
  2. select distinct hr.key_sk ,NEWID() as gened_unique_id
  3. from history_record hr
  4. where hr.unique_id is null;
  5. update hr
  6. set hr.unique_id = tmp.gened_unique_id
  7. from history_record hr
  8. inner join tmp on hr.key_sk = tmp.key_sk;
guykilcj

guykilcj2#

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

  1. with update_id_cte as (
  2. select key_sk, newid() as gened_unique_id
  3. from (select distinct key_sk from history_record where unique_id is null) t
  4. )
  5. update hr
  6. set hr.unique_id = cte.gened_unique_id
  7. from history_record hr
  8. inner join update_id_cte cte on hr.key_sk = cte.key_sk
dgiusagp

dgiusagp3#

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

  1. with update_id_cte as (
  2. select hr.key_sk, NEWID() as gened_unique_id
  3. from history_record hr
  4. where hr.unique_id is null
  5. group by hr.key_sk
  6. )
  7. update hr
  8. set hr.unique_id = cte.gened_unique_id
  9. from history_record hr join
  10. update_id_cte cte
  11. on hr.key_sk = cte.key_sk;

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

  1. with update_id_cte as (
  2. select hr.key_sk, coalesce(max(hr.unique_id), NEWID()) as gened_unique_id
  3. from history_record hr
  4. group by hr.key_sk
  5. )
  6. update hr
  7. set hr.unique_id = cte.gened_unique_id
  8. from history_record hr join
  9. update_id_cte cte
  10. on hr.key_sk = cte.key_sk
  11. where hr.unique_id is null;
展开查看全部

相关问题