如果查询返回null mysql,则count = 0

时间:2013-02-22 11:13:45

标签: mysql

我有mysql DB。

我正在运行以下查询。

SELECT cluster,
       infra_properties.property_name property,
       count(*)
FROM   raw_alerts,
       infra_properties
WHERE  infra_properties.parent_group = raw_alerts.cluster
       AND cluster = 'abuse-content'
       AND infra_properties.property_name = 'BigBro'
       AND timestamp BETWEEN '2012-12-24 00:00:00' AND '2012-12-24 23:59:59'
GROUP  BY cluster; 

我得到输出为null但我的要求是得到count = 0。如下所述。

+---------------+----------+----------+
| cluster       | property | count(*) |
+---------------+----------+----------+
| abuse-content | BigBro   |    0     |
+---------------+----------+----------+
1 row in set (0.30 sec)

1 个答案:

答案 0 :(得分:0)

如果2个表上没有匹配的记录,则不会返回任何行。

您可能需要做的是拥有一个包含集群和属性列的额外表,然后执行以下操作: -

SELECT a.cluster, a.property, count(c.id)
    FROM SomeExtraTable a
    LEFT OUTER JOIN raw_alerts b ON a.cluster = b.cluster AND AND b.cluster = 'abuse-content'
    LEFT OUTER JOIN infra_properties c 
ON a.property = c.property 
AND c.parent_group = b.cluster
AND c.property_name = 'BigBro' 
AND c.timestamp BETWEEN '2012-12-24 00:00:00' AND '2012-12-24 23:59:59'
    GROUP  BY  a.cluster, a.property

(我只猜测时间戳列在哪个表上)