2012-02-15 66 views
0

我有希望更新(如果以前沒有條件存在插入)的表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 
--------------------------------------------------------------------- 

我想填充server_status與其他表的ID和避免重複。

到目前爲止我有:

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

首先創建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'