2017-04-13 27 views
-3

表中沒有主鍵。如何在sql select查詢中顯示具有值的新列?

我的表像

col1 col2 col3 
12  34  35 
56  34  35 
13  56  35 
56  34  35 
12  56  34 

我想這顯示這樣的額外列的查詢:

col0 col1 col2 col3 
rox 12  34  35 
max 56  34  35 
bill 13  56  35 
rox 56  34  35 
sam 12  56  34 
+0

凡在額外的列值是從哪裏來的? –

+6

你爲什麼不呢? –

+0

所以鑑於你的表有「沒有主鍵」在'col0'中的值和現有列之間的關係是什麼? – APC

回答

0

要添加新列

alter table your_table 
    add col0 varchar2(10); 

「有在表中沒有主鍵。「

因此,這意味着col0中的值和現有列之間的關係基本上是隨機的,這使我們可以自由地填充新列。

下面是測試數據:

SQL> select * from your_table; 

COL0    COL1  COL2  COL3 
---------- ---------- ---------- ---------- 
        12   34   35 
        56   34   35 
        13   56   35 
        56   34   35 
        12   56   34 

SQL> 

這裏是使用批量操作來更新表中所有的行一個PL/SQL程序。

SQL> declare 
    2  -- this collection type will be available in all Oracle databases 
    3  new_col sys.dbms_debug_vc2coll := 
    4   sys.dbms_debug_vc2coll('rox','max','bil','rox','sam'); 
    5  your_table_rowids sys.dbms_debug_vc2coll; 
    6 begin 
    7 -- note: solution fits given data, so does not bother to handle large volumnes 
    8 select rowidtochar(yt.rowid) 
    9 bulk collect into your_table_rowids 
10 from your_table yt; 
11 
12 -- NB: this is not a loop, this is a bulk operation 
13 forall idx in your_table_rowids.first()..your_table_rowids.last() 
14  update your_table yt 
15   set yt.col0 = new_col(idx) 
16   where yt.rowid = chartorowid(your_table_rowids(idx)) 
17 ; 
18 end; 
19/

PL/SQL procedure successfully completed. 

SQL> 

的廢話與ROWID是必要的,因爲你的表沒有主鍵和重複行。

總之,這裏的結果:

SQL> select * from your_table 
    2/

COL0    COL1  COL2  COL3 
---------- ---------- ---------- ---------- 
rox    12   34   35 
max    56   34   35 
bil    13   56   35 
rox    56   34   35 
sam    12   56   34 

SQL> 
0

written an answer which uses DDL and UPDATE to change the database state我正確地讀8的問題的標題),所以這裏是選擇一個僞列COL0查詢。

有了這個測試數據:

SQL> select * from your_table 
    2/

     COL1  COL2  COL3 
---------- ---------- ---------- 
     12   34   35 
     56   34   35 
     13   56   35 
     56   34   35 
     12   56   34 

SQL> with nt as (
    2  select column_value as col0 
    3    , rownum as rn 
    4  from 
    5  table(sys.dbms_debug_vc2coll('rox','max','bil','rox','sam')) 
    6 ) 
    7 select nt.col0 
    8    , yt.col1 
    9    , yt.col2 
10    , yt.col3 
11 from nt 
12  join (select t.* 
13     , rownum as rn 
14   from your_table t) yt 
15  on yt.rn = nt.rn 
16/

COL0    COL1  COL2  COL3 
---------- ---------- ---------- ---------- 
rox    12   34   35 
max    56   34   35 
bil    13   56   35 
rox    56   34   35 
sam    12   56   34 

SQL> 
相關問題