
[英]Copy rows from and within same oracle SQL table and changing some column values
[英]Copy data within a table and changing values
我有一个名为USER_OPTIONS
的表。 如果我使用以下查询此表:
SELECT * FROM USER_OPTIONS
我得到以下结果:
现在,我需要将相同的值(A,1),(B,2),(C,3)等复制到同一张表中,但要更改USER_ID
值。 最终结果应为:
2 A 1
2 B 2
2 C 3
2 D 4
2 E 5
2 F 6
3 A 1
3 B 2
3 C 3
3 D 4
3 E 5
3 F 6
您可能会想:“非常简单,只需添加一个循环即可。” 但是这里有个问题……我只需要声明一下即可。 有没有办法做到这一点? 怎么样?
只需执行简单的INSERT INTO..SELECT即可 。
例如,
INSERT INTO user_options SELECT user_id + 1, code, code_value FROM user_options;
COMMIT;
SELECT * FROM user_options;
测试用例
SQL> SELECT * FROM user_options;
USER_ID C CODE_VALUE
---------- - ----------
2 A 1
2 B 2
2 C 3
2 D 4
2 E 5
2 F 6
6 rows selected.
SQL>
SQL> INSERT INTO user_options SELECT user_id + 1, code, code_value FROM user_options;
6 rows created.
SQL>
SQL> COMMIT;
Commit complete.
SQL>
SQL> SELECT * FROM user_options ORDER BY 1, 2, 3;
USER_ID C CODE_VALUE
---------- - ----------
2 A 1
2 B 2
2 C 3
2 D 4
2 E 5
2 F 6
3 A 1
3 B 2
3 C 3
3 D 4
3 E 5
3 F 6
12 rows selected.
SQL>
尝试这个
插入到user_options中从user_options中选择3,code_code_value;
您可以使用以下方法生成行:
select u.user_id, uo.code, uo.code_value
from (select 2 as user_id from dual union all select 3 as user_id from dual) u cross join
user_options uo;
如果您只想将它们放在同一张表中:
insert into user_option(user_id, code, code_value)
select 3, code, code_value
from user_options
where user_id = 2;
您可以进行简单的交叉连接,根据您的方案,您可以具有以下表格
CREATE TABLE [dbo].[Userid] (
[Id] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Code] (
[Code] VARCHAR (50) NOT NULL,
[Code_Value] INT NULL
);
然后如下查询
select * from userid,code order by Id,Code,Code_Value
希望能帮助到你....
当在user_options和包含所有所需user_id的表之间进行笛卡尔连接时,您将获得所需的结果
select usr.user_id, o.code_,o.code_value from
user_options o,
(select rownum user_id from dual connect by level <3 ) usr
其中“ usr”是所有user_id的列表。 我只生成1,2-可以通过级别条件进行修改。 或者,您也可以加入包含这些user_id的表。
看一下工作示例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.