开发者

SQL Update with subsubquery

I'm having a problem with the following update query in Oracle 11g:

update TABLE_A a set COL1 = 
  (SELECT b.COL2 FROM
    (SELECT ROWNUM AS ROW_NUMBER, b.COL2 from TABLE_B b where COL3 = a.COL4) 
   WHERE ROW_NUMBER = 2
  )

ORA-00904: "A"."COL4": invalid ID .

So, a.COL4 is not known in the subsubquery, but I don't have an idea how to开发者_如何学编程 solve this.

/Edit. What am I trying to do?

There are multiple records in TABLE_B for every record in TABLE_A. New requirements from the customer however: TABLE_A will get 2 new columns instead, while TABLE_B will be deleted. So a representation of the first record of the subquery will be written to the first new field and the same for the second one. First record is easy, since Mike C's solution can be used with ROW_NUMBER = 1.

Example rows:

TABLE_A

| col0 | col1 | col2 | col3 | col4 |
------------------------------------
|      |      |dummy2|dummy3|   1  |
------------------------------------
|      |      |dummy4|dummy5|   2  |
------------------------------------

TABLE_B

| col1 | col2 | col3 |
----------------------
|  d   |name1 |   1  |
----------------------
|  d   |name2 |   1  |
----------------------
|  d   |name3 |   1  |
----------------------
|  d   |name4 |   2  |
----------------------


TABLE_A after update

| col0 | col1 | col2 | col3 | col4 |
------------------------------------
| name1| name2|dummy2|dummy3|   1  |
------------------------------------
| name4|      |dummy4|dummy5|   2  |
------------------------------------


UPDATE TABLE_A a SET COL1 = 
  (SELECT b.COL2 FROM
    (SELECT ROWNUM AS ROW_NUMBER, b.COL2 FROM TABLE_B b, TABLE_A innerA WHERE COL3 = innerA.COL4) 
   WHERE ROW_NUMBER = 2
  )


Can you eliminate one of the subqueries like this?

update TABLE_A a set COL1 = 
(SELECT b.COL2 FROM TABLE_B b where COL3 = a.COL4 AND ROWNUM = 2)


Try

update TABLE_A a set COL1 = 
  (SELECT b.COL2 FROM
    (SELECT ROWNUM AS ROW_NUMBER, b.COL2 from TABLE_B b, TABLE_A a2 where b.COL3 = a2.COL4) 
   WHERE ROW_NUMBER = 2
  )

I'm assuming COL3 comes from table b, also why are you including selecting ROWNUM in the subquery? It can only be 2 from your WHERE clause.


I think this could be a possible solution to your problem but depending on the amount of data you're processing it could be really slow because there is no limiting factor for the inner statement.

update
  table_a upd
set upd.col1 = (
  select
    sub.col2
  from
    (
      select
        rownum as row_number,
        b.col2 as col2,
        b.col3 as col3
      from
        table_a a,
        table_b b
      where b.col3 = a.col4
    ) sub
  where sub.row_number = 2
    and sub.col3       = upd.col4
)


I solved this using a temporary table, deleting data from it as table A gets filled.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜