根据另一个表中的数据更改表

时间:2016-07-25 09:32:13

标签: mysql sql oracle

我有一个主表,比如说TABLE1

PLANT        JUNCTION     COST    Disct
LONDON        LD_1         10   1
LONDON        LD_2         11   2
LONDON        LD_3         12   5
SUTHERLAND    TE_R10       8    20
SUTHERLAND    TE_R10       8    20
SUTHERLAND    TE_R10       8    20
SUTHERLAND    TE_R11       9    23
SUTHERLAND    TE_R12      10    29
NY            TE_R8        2    5
NY            TE_R8        2    5
NY            TE_R9       11    10

我有另一张Table2这样的表:

PLANT         JUNCTION  FLATRATE
SUTHERLAND     TE_R10   0
NY             TE_R8    10

我的目的是从表1和表2中生成如下表所示的表:

PLANT   JUNCTION    CARRIERCOST Disct
LONDON      LD_1    10  1
LONDON      LD_2    11  2
LONDON      LD_3    12  5
SUTHERLAND  TE_R10  0   20
SUTHERLAND  TE_R10  0   20
SUTHERLAND  TE_R10  0   20
SUTHERLAND  TE_R11  9   23
SUTHERLAND  TE_R12  10  29
NY          TE_R8   10  5
NY          TE_R8   10  5
NY          TE_R9   11  10

即如果table2中的工厂名称和联结名称与table1匹配,则将table1的COST更新为table2的FLATRATE

2 个答案:

答案 0 :(得分:0)

MySQl

UPDATE T
SET S.Cost = ISNULL(T.COST,S.Cost)
FROM Table1 S
LEFT JOIN Table2 T ON S.PLANT = T.PLANT AND S.PLANT ;

答案 1 :(得分:0)

<强>的Oracle

CREATE TABLE table3
AS
   SELECT a.plant, a.junction, NVL (b.flatrate, a.cost) carriercost, a.disct
     FROM table1 a 
     LEFT OUTER JOIN table2 b ON a.plant = b.plant AND a.junction = b.junction