MySQL:比较两个表并将数据修改为一个

时间:2016-10-07 14:26:42

标签: mysql

我的数据库中有两个表:

表1:hussainalotcallplan1

Field    Type          Null    Key     Default  Extra   
-------  ------------  ------  ------  -------  --------
concode  varchar(20)   NO      PRI     (NULL)           
rate     double        YES             (NULL)           
vendor   varchar(100)  YES             (NULL)
diff     varchar(20)   YES             'NEW'

表2:tempratediff

Field   Type         Null    Key     Default  Extra   
------  -----------  ------  ------  -------  --------
id      varchar(20)  NO      PRI     (NULL)           
rate    double       YES             (NULL)           

我想比较每个ID的两个表的比率,并将结果放在diff表的hussainalotcallplan1列下。

这两个表格相关为hussainalotcallplan1.concode = tempratediff.id

示例数据:hussainalotcallplan1

concode rate vendor diff 91 0.05 gbm new

tempratediff

id rate 91 0.04

我要计算两种费率之间的差异,并将它们之间的差异插入hussainalotcallplan1.diff

我试过这个:update hussainalotcallplan1 set diff = SELECT CASE WHEN (SELECT c.concode FROM hussainalotcallplan1 ) IN (SELECT t.id FROM tempratediff) THEN (c.rate-t.rate) END AS diff FROM hussainalotcallplan1 c, tempratediff t WHERE c.concode = t.id;

有谁可以给​​我一个线索?在此先感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用update-join语法:

UPDATE hussainalotcallplan1 h
JOIN   tempratediff t ON h.concode = t.id
SET    h.diff = h.rate - t.rate

答案 1 :(得分:0)

    UPDATE hp 
SET hp.diff = CAST(hp.rate - td.rate AS VARCHAR)
    FROM hussainalotcallplan1 hp
    JOIN tempratediff td On hp.concode = td.id

我没有对此进行测试,但希望它是你的目标