SQL:从具有匹配对象名称的另一个表中插入列

时间:2015-12-21 20:38:00

标签: mysql sql

我有两张桌子:

表1:
            vm_name | HOST_NAME
    vm1 | server1的
vm2 | server1的
vm3 |服务器2

表2:object_id | OBJECT_NAME
1 | server1的
2 | VM1
3 | VM3
4 |服务器2
5 | VM2

我想在表1中添加两列(或创建新的整个表),这些列将显示vm_name,object_id,host_name,object_id。我还想将object_id列名更改为vm_id和host_id。

输出表如下所示:
           vm_name | vm_id | host_name | HOST_ID
vm1 | 2 | server1 | 1
  vm2 | 5 | server1 | 1
vm3 | 3 | server2 | 4个

关于如何做到这一点的任何想法? 到目前为止,我正在使用join来匹配:vm_name |的object_id

SELECT table1.vm_name, table2.object_id
FROM table1
INNER JOIN table2
ON table1.vm_name = table2.object_name
ORDER BY table1.vm_name;

但是如何同时添加两列?

1 个答案:

答案 0 :(得分:1)

再次加入table2

select t1.vm_name, 
       t2.object_id as vm_id,
       t1.host_name,
       t3.object_id as host_id
from table1 t1
       join table2 t2 on t1.vm_name = t2.object_name
       join table2 t3 on t1.host_name = t3.object_name
order by t1.vm_name