Mysql 需要添加DISTINCT才能加入

Mysql 需要添加DISTINCT才能加入,mysql,Mysql,我试图在我的查询中使用DISTINCT,但是我无法获得正确的语法来获得我期望的结果。我发表了两篇不同的堆栈溢出帖子,我想我终于明白了如何包含获得帮助所需的所有信息 我在DB Fiddle上构建了一个共享空间,其中包含已加载的所有信息: 这是我的问题,我已经能够拼凑起来 SELECT map.newvalue as 'Model of Phone', Count(*) as 'Number of Phones' FROM hosts h LEFT JOIN items i

我试图在我的查询中使用DISTINCT,但是我无法获得正确的语法来获得我期望的结果。我发表了两篇不同的堆栈溢出帖子,我想我终于明白了如何包含获得帮助所需的所有信息

我在DB Fiddle上构建了一个共享空间,其中包含已加载的所有信息:

这是我的问题,我已经能够拼凑起来

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 huint.value=map.value AND i.name LIKE '%Model of the Phone'
GROUP BY map.newvalue;
现在查询返回

Model of Phone  Number of Phones
Cisco 7841      8
Cisco 7940      2
但是我希望在items表column itemid上使用DISTINCT,这样我们就只能返回了

Model of Phone  Number of Phones
Cisco 7841      3
Cisco 7940      1

谢谢你的帮助

如果
不重复
计数
会发生什么

SELECT map.newvalue as 'Model of Phone'
    , Count(DISTINCT i.name) as 'Number of Phones'
FROM hosts h
JOIN items i ON h.hostid = i.hostid
JOIN history_uint huint ON i.itemid = huint.itemid
JOIN mappings map ON i.valuemapid = map.valuemapid AND huint.value=map.value 
WHERE i.name LIKE '%Model of the Phone'
GROUP BY map.newvalue;

由于您特别希望从items表中获得不同的记录,这将为您提供电话类型,因此您的查询可能如下所示:

SELECT map.newvalue as 'Model of Phone', Count(distinct i.itemid) 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 huint.value=map.value AND i.name LIKE '%Model of the Phone'
GROUP BY map.newvalue;

当您进行计数(*)时,它返回8行作为计数的原因是,当您将itemid(来自历史记录)添加到选择字段时,每一行呈现不同。因此,总体而言,字段不明显,因此返回所有8行。

在左侧联接中,按最右侧表中的列进行分组(通常)没有多大意义。谢谢raj。。。Eric在你之前刚刚发布过,但也感谢你的帮助和详细解释
SELECT map.newvalue as 'Model of Phone', Count(distinct i.itemid) 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 huint.value=map.value AND i.name LIKE '%Model of the Phone'
GROUP BY map.newvalue;