不同类型

时间:2017-08-04 11:44:53

标签: mysql

我在MySQL数据库中有2个表,主机和events,可以加入thanks和ID字段。 对于hosts表格,我的查询感兴趣的特定字段是name;对于eventstype。 如果我在它们之间建立连接,则示例结果为:

enter image description here

因此,在此图像中,您可以看到Host Achille ha 4事件:OS类型2,应用程序时间1和服务类型1。

我的问题是:使用聚合器运算符,是否可以创建一个表格,对于每个主机,我可以显示有多少事件按类型划分? 更具体地说,所需的表可能有这个标题:

enter image description here

在以前的例子中,可能会返回:

| Achille | 1 | 2 | 1 |
| Aiace   | 1 | 1 | 0 |
| Ulisse  | 0 | 0 | 1 |

我的第一次尝试是这个查询:

    SELECT hosts.name, count(e1.type) as Applications, count(e2.type) as OS, count(e3.type) as Type 
    FROM hosts JOIN events e1 ON hosts.id = e1.host_id 
    JOIN events e2 ON hosts.id = e2.host_id 
    JOIN events e3 ON hosts.id = e3.host_id 
    WHERE e1.type = 'Applications' AND e2.type = 'OS' AND e3.type = 'Services' 
GROUP BY hosts.name;

但不起作用。

1 个答案:

答案 0 :(得分:2)

您不需要多次加入活动表。只做条件聚合。

SELECT h.name, 
    count(case when e.type = 'Applications' then 1 end) as Applications,
    count(case when e.type = 'OS' then 1 end) as OS,
    count(case when e.type = 'Services' then 1 end) as Services
FROM hosts h
JOIN events e ON h.id = e.host_id 
GROUP BY h.name;

或简明扼要地,使用sum

SELECT h.name, 
    sum(e.type = 'Applications') as Applications,
    sum(e.type = 'OS') as OS,
    sum(e.type = 'Services') as Services
FROM hosts h
JOIN events e ON h.id = e.host_id 
GROUP BY h.name;