mysql update insert join避免重复

时间:2012-02-15 18:37:51

标签: mysql

我有一个我希望更新的表(如果不存在先前条件,则插入)

servers table              clusters table              datacenters table  

server_id | server_name     cluster_id | cluster_name   datacenter_id | datacenter_name
-----------------------     -------------------------   -------------------------------
1           server1          1           cluster1        1               datacentereast
2           server7          3           Cluster22       5               datacenterwest


server_status table

status_id   |    status_server   | status_cluster | status_datacenter
---------------------------------------------------------------------

我希望用其他表的id填充server_status并避免重复。

到目前为止,我有:

sql_string = """  
INSERT into server_status (status_datacenter,status_cluster, status_server)
    SELECT 
        d.datacenter_id,c.cluster_id,s.server_id 
    FROM 
        datacenters as d, clusters as c, servers as s
    WHERE
        d.datacenter_name = \'%s\' 
        AND c.cluster_name = \'%s\'
        AND s.server_name = \'%s\'
        AND d.datacenter_id != status_datacenter
        AND c.cluster_id != status_cluster
        AND s.server_id != status_server;
    """ % (datacenter,cluster,server)

上述内容失败了:

_mysql_exceptions.OperationalError: (1054, "Unknown column 'status_datacenter' in 'where clause'")

打印出一个实际的sql命令:

INSERT into server_status (status_datacenter,status_cluster, status_server) 
 SELECT d.datacenter_id,c.cluster_id,s.server_id 
  FROM datacenters as d, clusters as c, servers as s 
   WHERE d.datacenter_name = 'SDDC' 
   AND c.cluster_name = 'qboc37' 
   AND s.server_name = 'ap30' 
   AND d.datacenter_id != status_datacenter 
   AND c.cluster_id != status_cluster 
   AND s.server_id != status_server; 

1 个答案:

答案 0 :(得分:1)

首先在server_status (status_datacenter,status_cluster, status_server)上创建一个唯一索引,然后

INSERT IGNORE into server_status (status_datacenter,status_cluster, status_server) 
 SELECT d.datacenter_id,c.cluster_id,s.server_id 
  FROM datacenters as d, clusters as c, servers as s 
   WHERE d.datacenter_name = 'SDDC' 
   AND c.cluster_name = 'qboc37' 
   AND s.server_name = 'ap30'