将INNER JOIN添加到我的MySQL查询中,这样我就可以使用DISTINCT

时间:2019-03-18 06:03:57

标签: mysql grafana zabbix

我正在使用4个表-项目,主机,历史记录,映射

物品

hostid,itemid,name,valuemapid
10761,304827,Phone 33 44 55 66 77 88:Model of the Phone,68
10761,304827,Phone 33 44 55 66 77 88:Model of the Phone,68
10761,304827,Phone 33 44 55 66 77 88:Model of the Phone,68
10761,304828,Phone 33 44 55 66 88 88:Model of the Phone,68
10761,304828,Phone 33 44 55 66 88 88:Model of the Phone,68
10761,304828,Phone 33 44 55 66 88 88:Model of the Phone,68
10761,304829,Phone 33 44 55 77 77 88:Model of the Phone,68
10761,304829,Phone 33 44 55 77 77 88:Model of the Phone,68
10761,304820,Phone 33 44 44 66 77 88:Model of the Phone,72
10761,304820,Phone 33 44 44 66 77 88:Model of the Phone,72

主机

hostid,name
10761,CUCM2

历史

itemid,value
304827,109
304828,109
304829,109
304829.110

映射

valuemapid,value,newvalue
68,109,Cisco 7841
72,110,Cisco 7940

我写了一个查询给我手机的型号和该型号的数量,但它在计算重复项。有人告诉我我需要添加一个内部联接,但是我不知道该怎么做。有人可以帮助我更改查询,以使“ Items”表具有INNER JOIN,这样它将删除所有重复的ItemID。

SELECT map.newvalue as 'Model of Phone', Count(*) as 'Number of Phones'
FROM items i, hosts h, history huint, mappings map
WHERE h.hostid=i.hostid AND h.name='$Hosts' AND i.itemid=huint.itemid AND i.valuemapid=map.valuemapid AND huint.value=map.value AND i.name LIKE '%Model of the Phone'
GROUP BY map.newvalue
LIMIT 100;

返回

Model of Phone, Number of Phones
Cisco 7841, 8
Cisco 7940, 2

谢谢!

**更新**使用LEFT JOIN但无法弄清楚如何使用DISTINCT

SELECT map.newvalue as 'Model of Phone', Count(*) as 'Number of Phones'
FROM hosts h
    LEFT JOIN items i
        ON h.hostid=i.hostid
    LEFT JOIN history_uint huint
        ON i.itemid=huint.itemid
    LEFT JOIN mappings map
        ON i.valuemapid=map.valuemapid
WHERE h.name='$Hosts' AND huint.value=map.value AND i.name LIKE '%Model of the Phone'
GROUP BY map.newvalue
ORDER BY 'Item Name' DESC
LIMIT 100;

1 个答案:

答案 0 :(得分:1)

这是您使用1992年以后的语法重写的查询...

SELECT m.newvalue 'Model of Phone'
     , Count(*) 'Number of Phones'
  FROM items i
  JOIN hosts h
    ON h.hostid = i.hostid 
  JOIN history y
    ON y.itemid = i.itemid
  JOIN mappings m
    ON m.valuemapid = y.valuemapid 
   AND y.value = m.value
 WHERE h.name = '$Hosts' -- this is insecure
   AND i.name LIKE '%Model of the Phone' -- and this cannot use an index 
 GROUP 
    BY m.newvalue
 ORDER
    BY m.newvalue
 LIMIT 100;

现在,要获取更多帮助,请参见Why should I provide an MCVE for what seems to me to be a very simple SQL query?