mysql将数据从表复制到另一个具有相同值的数据?

时间:2018-08-08 12:53:42

标签: mysql database

我正在尝试从另一个表更新我的表

我需要根据SIM卡号从表changeip中的new_IP更新表1中的IP(这两个表都相同)

我已经尝试按照这里所说的去做: mysql update column with value from another table

I get error "IP can't be null"

这是我在命令行中写的

    UPDATE table1 
SET table1.IP = (
    SELECT changeip.New_IP 
    FROM changeip
    WHERE table1.SIM_NEW = changeip.SIM_Number 
);

我在做什么错了?

****************更新

这是表1

'10 .226.202.169','8997250000031944123'

'10 .226.202.170','8997250000031944131'

'10 .226.202.173','8997250000031944164'

'10 .136.136.101','8997250400019201597'

'10 .136.136.102','8997250400019201589'

'10 .136.136.103','8997250400019201571'

'10 .136.136.104','8997250400019201563'

以此类推........

这是变更表

'10 .226.202.169','8997250000031944123','10.136.137.221'

'10 .226.202.170','8997250000031944131','10.136.137.222'

'10 .226.202.173','8997250000031944164','10.136.137.223'

'10 .226.202.174','8997250000031944172','10.136.137.224'

'10 .226.202.175','8997250000031944180','10.136.137.225'

'10 .226.202.177','8997250000031944206','10.136.137.226'

谢谢,

4 个答案:

答案 0 :(得分:0)

ALTER table1 MODIFY IP varchar(20) null;

如果其他表包含空值,则将该列从非空更改为空

答案 1 :(得分:0)

您需要joinupdate

 UPDATE table1 t
    inner join changeip p
    on t.SIM_NEW= p.SIM_Number
   and t.IP=p.old_ip
    SET t.IP =p.New_IP

答案 2 :(得分:0)

如果要更新changeip表上具有IP的服务器,而将那些没有新IP的服务器保留为旧IP,这应该可以工作:

UPDATE table1 
SET table1.IP = (
    SELECT changeip.New_IP 
    FROM changeip
    WHERE table1.SIM_NEW = hangeip.SIM_Number 
    AND hangeip.New_IP IS NOT NULL
);

答案 3 :(得分:0)

获得所需结果的一种简单方法如下:

根据您的数据,开始表是

enter image description here

enter image description here

如果您运行查询

UPDATE table1, changeip 
  SET table1.IP = changeIP.old_IP 
  WHERE table1.SIM = changeip.SIM_Number

结果如下:

enter image description here

我相信这是理想的结果。上面的大多数建议都缺少UPDATE语句中的WHERE子句,这就是为什么它们失败的原因。