mysql查询显示来自一个ID列

时间:2017-03-09 08:44:33

标签: mysql join many-to-many

我正在尝试查找此查询,我想显示哪些主机使用我的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

从名称输出,来自表主机的hostid 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查询的组合。我感觉自己如此接近,但我无法得到它。

非常感谢任何帮助!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这是一个基本问题。您应该了解有关SQL语法的更多信息,例如链式连接,从不同的表中访问相同的列名。

示例代码:

def collection_exists?(event_list)
  return unless self.class.method_defined?(event_list)
  eval("self.#{event_list.to_s}").any?
end

答案 2 :(得分: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 

使用它,它的工作原理

相关问题