我想使用首先使用列的选项更新第三个
|first #|second #|third #|
|_______|________|_______|
|___1___|___1____|_null__|
|___5___|___2____|_null__|
|___3___|___6____|_null__|
|___2___|___4____|_null__|
在伪代码中:
for row in table:
row.third = result_of_a_select(row.first)
SQL的等价物是什么?
我的错误尝试:
update example_table
set third=
(
SELECT MAX(CDARTI) FROM
(
SELECT A.CDARTI
FROM PGMR.UT_ART_CODALT T,
PGMR.MRP_ARCH_ARTICOLI A
WHERE
A.CDARTI = T.CDARTI AND
T.CDARTI = first
UNION
SELECT A.CDARTI
FROM PGMR.UT_ART_CODALT T,
PGMR.MRP_ARCH_ARTICOLI A
WHERE
A.CDARTI = T.CDARTI_A AND
T.CDARTI = first
UNION
SELECT A.CDARTI
FROM PGMR.UT_ART_CODALT T,
PGMR.MRP_ARCH_ARTICOLI A
WHERE
A.CDARTI = T.CDARTI AND
T.CDARTI_A = first
UNION
SELECT A.CDARTI
FROM PGMR.UT_ART_CODALT T,
PGMR.MRP_ARCH_ARTICOLI A
WHERE
A.CDARTI = T.CDARTI_A AND
T.CDARTI = (SELECT T2.CDARTI FROM PGMR.UT_ART_CODALT T2 WHERE T2.CDARTI_A = first)
)
);
commit;
答案 0 :(得分:0)
适合我。
update t1 set third = (select third from t2 where t2.first = t1.first);
Fiddle(切换到MySql DB,因为我无法让Oracle在其中工作,但也针对我的本地Oracle进行了测试)。
问题不在于方法,而是在您的查询中。要解决此问题,您需要提供Minimal, Complete, and Verifiable example。
答案 1 :(得分:0)
简化的测试用例:
SQL> create table yourTable (first, second, third) as (
2 select 1, 1, cast (null as number) from dual union all
3 select 5, 2, cast (null as number) from dual union all
4 select 3, 6, cast (null as number) from dual union all
5 select 2, 4, cast (null as number) from dual
6 );
Table created.
SQL> update yourTable t
2 set third = (select t.first * 2 from dual);
4 rows updated.
SQL> select * from yourTable;
FIRST SECOND THIRD
---------- ---------- ----------
1 1 2
5 2 10
3 6 6
2 4 4
SQL>
答案 2 :(得分:0)
为了使它更有趣/说明性示例,我使用映射表中的值更新third
列并包含重复值。
您可以使用MERGE
并匹配伪列ROWID
:
Oracle安装程序:
CREATE TABLE table_name ( first, second, third ) AS
SELECT 1, 1, CAST( NULL AS NUMBER ) FROM DUAL UNION ALL
SELECT 5, 2, NULL FROM DUAL UNION ALL
SELECT 3, 6, NULL FROM DUAL UNION ALL
SELECT 2, 4, NULL FROM DUAL UNION ALL
SELECT 3, 4, NULL FROM DUAL;
CREATE TABLE table_name_map ( first, value ) AS
SELECT 1, 9 FROM DUAL UNION ALL
SELECT 2, 8 FROM DUAL UNION ALL
SELECT 3, 7 FROM DUAL UNION ALL
SELECT 4, 6 FROM DUAL UNION ALL
SELECT 5, 5 FROM DUAL;
<强>更新强>:
MERGE INTO table_name dst
USING ( SELECT t.ROWID AS ri,
m.value
FROM table_name t
INNER JOIN table_name_map m
ON ( t.first = m.first )
) src
ON ( src.ri = dst.ROWID )
WHEN MATCHED THEN
UPDATE SET third = src.value;
<强>结果强>:
FIRST SECOND THIRD
----- ------ -----
1 1 9
5 2 5
3 6 7
2 4 8
3 4 7