繁体   English   中英

mysql 查询显示来自一个 ID 列的多个表

[英]mysql query show multiple tables from one ID column

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

该表有 3 列:host_template id、hostid、templateid

表 hosts 有许多列,但还包含:hostid、name 其中 hostid 包含主机以及模板。 表 hosts 确实有一个 templateid 列,但它没有被使用。

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

来自表 hosts_templates 的 output
表 hosts_templates 的输出

output 来自名称,hostid 来自表 hosts
来自名称的输出,来自表 hosts 的 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;

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

问题是我不能为第二列选择不同的名称,所以它只是复制了第一列,这不是我想要的......而且由于我已经内部加入了 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

这是一个基本问题。 您应该了解有关 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;

当您从一张表中选择数据时,即仅使用 host_templates

SELECT id,hosts_templates.hostid,hosts_templates.templateid FROM hosts,host_templates WHERE hosts.id = hosts_templates.hostsid OR hosts.id=hosts_templates.templateid 

使用它,它有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM