我试图找到这个查询,我想在其中显示哪些主机使用我的 Zabbix 表中的哪个模板。唯一的问题是主机和模板注册在同一个表中。它们在表中混合,例如 ID 11813 是主机,11815 是模板。 现在我找到了一个表,其中定义了这两者之间的关系:hosts_templates。
该表有 3 列: host_template id、hostid、templateid
hosts 表有很多列,但还包含:hostid、名称,其中 hostid 包含主机和模板。表主机确实有一个 templateid 列,但它没有被使用。
在表hosts_templates中,我可以看到哪些主机使用哪个模板。唯一的问题是我看到了 ID,并且想查看与该 ID 匹配的名称。 到目前为止我所拥有的:
表hosts_templates的输出
来自名称的输出,来自表主机的主机ID
到目前为止我已经尝试过:
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;
这些查询的输出显示了我的解决方案的一半,但有重复。
问题是我无法为第二列选择不同的名称,因此它只是重复第一列,这不是我想要的...并且由于我已经内部加入了主机ID,所以我无法这样做第二次。所以我需要上面 2 个 sql 查询的组合。我感觉我已经很接近了,但我就是无法理解。
任何帮助将不胜感激!
P粉6708387352024-03-27 09:23:21
这是一个基本问题。您应该了解有关 SQL 语法的更多信息,例如链式联接、从不同表访问相同的列名。
示例代码:
select h1.name, h2.name from hosts_templates ht inner join hosts h1 on ht.hostid = h1.hostid inner join hosts h2 on ht.templateid = h2.hostid;
P粉7294365372024-03-27 00:41:12
您必须加入两次。为表指定不同的别名,以便您可以区分它们。
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