如何更新随机oracle另一个表

时间:2017-08-02 10:49:07

标签: sql oracle oracle11g

我有表contacts

ID       CONTACT_ID      TYPE_ID
1            5               1
2            8               1
3            9               1                        
4            12              2        
5            13              1        
6            17              2                          
7            22              2                        
8            23              2    
9            25              1      
10           33              2                   
11           34              2                       
12           48              1      
.            ...             ...    
n            n               2

如何更新contact_id随机,但不能更改type_id(其中type_id = 1随机更新此联系人或type_id = 2->随机更新此联系人) 例如

ID       CONTACT_ID      TYPE_ID
    1            9               1
    2            13              1
    3            8               1                        
    4            17              2        
    5             5              1        
    6            22              2                          
    7            12              2                        
    8            33              2    
    9            48              1      
    10           34              2                   
    11           23              2                       
    12           25              1      
    .            ...             ...    
    n            n               2

1 个答案:

答案 0 :(得分:2)

有趣,虽然有点误导性的问题。这merge对我有用:

merge into contacts c
using (
    with t as (
        select c.*, 
               row_number() over (partition by type_id order by id) rn1,
               row_number() over (partition by type_id order by dbms_random.value) rn2 
          from contacts c)
    select t1.id, t1.type_id, t1.contact_id, 
           (select contact_id 
              from t t2 where type_id = t1.type_id and rn1 = t1.rn2) as contact_new
      from t t1) s
on (c.id = s.id)
when matched then update set contact_id = s.contact_new;

首先,我生成了由type_id分区并按idrn1)和随机(rn2)排序的数字。你可以看到它分别运行内部查询。在下一步中,我在merge中使用此查询作为源数据。