如何在sql select查询中显示具有值的新列?
问题描述:
表中没有主键。如何在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
答
要添加新列
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>
答
有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>
凡在额外的列值是从哪里来的? –
你为什么不呢? –
所以鉴于你的表有“没有主键”在'col0'中的值和现有列之间的关系是什么? – APC