简体   繁体   中英

In SQL How do I copy values from one table to another based on another field's value?

Okay I have two tables

VOUCHERT with the following fields

ACTIVATIONCODE
SERIALNUMBER
VOUCHERDATADBID 
UNAVAILABLEAT   
UNAVAILABLEOPERATORDBID 
AVAILABLEAT 
AVAILABLEOPERATORDBID   
ACTIVATIONCODENEW   
EXT1    
EXT2    
EXT3    
DENOMINATION -- I added this column into the table.

and the second table is VOUCHERDATAT with the following fields

VOUCHERDATADBID
BATCHID
VALUE
CURRENCY
VOUCHERGROUP
EXPIRYDATE
AGENT
EXT1
EXT2
EXT3

What I want to do is copy the corresponding VALUE from VOUCHERDATAT and put it into DENOMINATION of VOUCHERT. The linking between the two is VOUCHERDATADBID. How do I go about it?

It is not a 1:1 mapping. What I mean is there may be 1000 SERIALNUMBERS with a same VOUCHERDATADBID. And that VOUCHERDATADBID has only entry in VOUCHERDATAT, hence one value. Therefore, all serial numbers belonging to a certain VOUCHERDATADBID will have the same value.

Will JOINS work? What type of JOIN should I use? Or is UPDATE table the way to go?

Thanks for the help !!

Your problem is one of design. None of your tables are in any of the normal forms, not even in the first normal form (1NF). You should not add a column to the VOUCHERT table, but create a new table (pick the name) with the following columns: SERIALNUMBER , VALUE , VOUCHERDATADBID (maybe ACTIVATIONCODE too - need to know the primary key on VOUCHERT to be sure if ACTIVATIONCODE should be included in the new table). Normalization is the database design process that aims to resolve any possible INSERT / UPDATE / DELETE anomalies. This should solve your INSERT issue.

Hope this helps.

You can do a join between these two tables and you will get a 'view'. You can update this view like:

UPDATE (SELECT * 
        FROM VOUCHERT A JOIN VOUCHERDATAT B 
             ON A.VOUCHERDATADBID = B.VOUCHERDATADBID) 
SET DENOMINATION = VALUE;

You may put outer join if you need.

VOUCHERDATADBID MUST BE PRIMARY KEY in VOUCHERDATAT and FOREIGN KEY in VOUCHERT, otherwise you will get an error:

ORA-01779: cannot modify a column which maps to a non key-preserved table
update  (
        select  v.DENOMINATION
        ,       vd.VALUE
        from    VOUCHERT v
        join    VOUCHERDATAT vd
        on      vd.VOUCHERDATADBID = v.VOUCHERDATADBID
        ) t
set     t.DENOMINATION = t.Value

If the voucherdatadbid is not a primary key, this should work:

UPDATE vouchert
   SET denomination =
       (SELECT MAX(value)
          FROM voucherdatat
         WHERE voucherdatadbid = vouchert.voucherdatadbid);

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