简体   繁体   中英

Include data in a table looking in every insert if there is a match with the table values

I need to insert data from one table into another, but this insert must look into the table which receives data to determine if there is a match or not, and if it is, don't insert new data.

So, i have the next tables (NODE_ID refers to values in NODE1 and NODE2, think about lines with two nodes everyone) :

Table A:
| ARC | NODE1 | NODE2 | STATE |
| x   |  1    |  2    |   A   |
| y   |  2    |  3    |   A   |
| z   |  3    |  4    |   B   |

Table B:
| NODE_ID| VALUE |
|    1   |   N   |
|    2   |   N   |
|    3   |   N   |
|    4   |   N   |

And want the next result, that relates NODE_ID with ARCS and write in the result table the value of STATE from ARCS table, only one result for each NODE , because if not, i would have more than one row for the same NODE:

Table C result:
| NODE_ID| STATE |
|    1   |   A   |
|    2   |   A   |
|    3   |A(or B)|

I tried to do this with CASE statement with EXISTS, IF , and NVL2() and so on in the select but have no result at this time.

Any idea about how could i write this query?

Thank you very much for your help


Ok guys, i edit my message to explain how i did it finally, i've also changed a little bit my first message to make it more clear to undestand because we had problems with that.

So finally i used this query, that @mathguy introduced to me:

merge into Table_C c
   using (select distinct b.NODE_ID as nodes, a.STATE
          from Table_A a, Table_B b
          where (b.NODE_ID=a.NODE1 or b.NODE_ID=a.NODE2) s
   on (s.nodes=c.NODE_ID)

when not matched then
  insert (NODE_ID, STATE)
  values (s.nodes, s.STATE)

That's all

This can be done with insert , but often when you update one table with values from another, the merge statement is more powerful (more flexible).

merge into table_c c
  using ( select arc, min(state) as state from table_a group by arc ) s
  on (s.arc = c.node_id)
when not matched then insert (node_id, state)
  values (s.arc, s.state)
;

Thanks to @Boneist and @ThorstenKettner for pointing out several syntax errors (now fixed).

If table C does not yet exist, use a create select statement:

create table c as select arc as node_id, state from a;

In case there can be duplicate arc (not shown in your sample) you'd need aggregation:

create table c as select arc as node_id, min(state) as state from a group by arc;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM