我有一个新信息的临时表tmp_c
,我需要将其插入metric
表:
mysql> select host, metric, value from tmp_c limit 2;
+----------+----------+--------+
| host | metric | value |
+----------+----------+--------+
| host1 | % | 86 |
| host2 | Kbs | 6529 |
+----------+----------+--------+
mysql> select * from hostID limit 1;
+----+--------------+
| id | name |
+----+--------------+
| 1 | host1 |
+----|--------------+
mysql> select * from metricID limit 1;
+----+------------+
| id | metric |
+----+------------+
| 1 | % |
+-----------------+
mysql> select id, hostID, metricID, value from metric limit 1;
+----------+----------+-----------+---------+
| id | hostID | metricID | value |
+----------+----------+-----------+---------+
| 1 | 1 | 1 | 86 |
| 2 | 1 | 2 | 7765 |
+----------+----------+-----------+---------+
如何查找hostID和metricID的外键,并将tmp_c
中的数据插入metric
?
我使用下面的代码只使用一个外键关系在不同的表中进行另一个查询:(但在这种情况下不能使用两个)。也许使用视图?
INSERT IGNORE into host(cluster_id, name, numcpu, cpu_tot_mhz, mem_tot)
SELECT c.id as cluster_id, t.Entity as name, t.numcpu as numcpu,
t.CpuTotalMhz as cpu_tot_mhz, `Total Memory` as mem_tot from tmp_c t
INNER JOIN cluster c on c.name = t.Cluster;
答案 0 :(得分:1)
只需使用两个连接:
insert into metric(hostid, metricid, value)
select h.id, m.id, c.value
from tmp_c c join
host h
on c.host = h.name join
metricid m
on c.metric = m.metric;
这假设id是自动递增的,因此不需要传入。