【问题标题】:How to update random oracle another table如何更新随机oracle另一个表
【发布时间】:2017-08-02 10:49:07
【问题描述】:

我有桌子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

【问题讨论】:

  • 你的问题没有意义。在这种情况下,所需的结果会有所帮助。
  • 您想编写一个可以这样做的程序,还是只想要一个查询?
  • 我只需要查询
  • 我想更新随机但现有的值,而不是生成新的contact_id

标签: sql oracle oracle11g


【解决方案1】:

有趣,但有点误导性的问题。这个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 分区并由id (rn1) 和随机(rn2) 排序的数字。您可以看到它单独运行内部查询。在下一步中,我使用merge 中的这个查询作为源数据。

【讨论】:

    猜你喜欢
    • 2015-06-27
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多