如何使用MySQL查詢顯示一個ID欄位中的多個表格
P粉207483087
P粉207483087 2024-03-26 10:18:45
0
2
309

我試圖找到這個查詢,我想在其中顯示哪些主機使用我的 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粉207483087
P粉207483087

全部回覆(2)
P粉670838735

這是一個基本問題。您應該了解有關 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粉729436537

您必須加入兩次。為表指定不同的別名,以便您可以區分它們。

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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!