我正在尝试找到此查询,以在其中显示哪些主机使用Zabbix表中的哪个模板。唯一的问题是主机和模板在同一表中注册。它们在表中混合在一起,例如ID 11813为主机,11815为模板。
   现在,我找到了一个表,其中定义了这两个表之间的关系:hosts_templates。

该表有3列:
   一个host_template id,hostid,templateid

表主机具有许多列,但也包含:主机ID,其中主机ID包含主机和模板的名称。表主机确实具有templateid列,但未使用。

在表hosts_templates中,我可以看到哪些主机使用了哪个模板。唯一的问题是我看到了ID,并且想看到与该ID匹配的名称。
到目前为止,我有:

表hosts_templates的输出


名称输出,表主机的hostid


到目前为止我尝试过的是:

select name, name
  from hosts_templates
 inner join hosts on hosts_templates.hostid = hosts.hostid;

select name, name
  from hosts_templates
 inner join hosts on hosts_templates.templateid = hosts.hostid;


这些查询的输出显示了我的解决方案的一半,但是重复了。

问题是我无法为第二列选择其他名称,因此它只是复制了第一列,这不是我想要的...而且由于我已经内部加入了hostid,因此我无法第二次这样做。因此,我需要上面2个sql查询的组合。我有种感觉,我很亲近,但我无法理解。

任何帮助将不胜感激!

最佳答案

您必须加入两次。为表提供不同的别名,以便您可以区分它们。

SELECT h1.name as host_name, h2.name AS template_name
FROM hosts_template AS t
JOIN hosts AS h1 ON t.hostid = h1.hostid
JOIN hosts AS h2 ON t.hosttemplateid = h2.hostid

09-30 15:46
查看更多