mysql 查询从一个 ID 列显示多个表

问题描述 投票:0回答:3

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

此表有 3 列: host_template id, hostid, templateid

主机表有很多列,但也包含:hostid,名称,其中 hostid 包含主机和模板。表主机确实有一个 templateid 列,但它没有被使用。

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

表 hosts_templates 的输出
output from table hosts_templates

name 输出,hostid 从表 hosts 输出
output from name, hostid from table hosts

到目前为止我尝试了什么:

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 查询的组合。我有一种感觉,我是如此接近,但我就是无法得到它。

任何帮助将不胜感激!

mysql join many-to-many
3个回答
0
投票

你必须参加两次。给表不同的别名,这样你就可以区分它们。

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

0
投票

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

0
投票

当您从一个表中选择数据时,即 host_templates ony

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

使用它,它有效

© www.soinside.com 2019 - 2024. All rights reserved.