【问题标题】:Include rows which don't match with IN() clause包括与 IN() 子句不匹配的行
【发布时间】:2020-06-15 18:56:04
【问题描述】:

我有一个名为log 的表,其中包含多个应用程序发送的日志。此表有一个名为 referencevarchar 字段。

我在 Grafana 中有一个表格面板,其中显示了我们按 reference 值分组的日志数量。因此,用户在 Grafana 上的文本字段中键入一个或多个值,例如 'ref1', 'ref2', 'ref3',然后会触发这样的查询:

SELECT reference, count(id)
FROM db.log
WHERE reference IN('ref1', 'ref2', 'ref3')
GROUP BY reference

到目前为止一切顺利,它按预期工作。我想做的是用count=0 显示一行,以防给定reference 的日志不存在。我知道我可以使用UNION 添加任意行,但我认为我无法在 Grafana 中动态添加。

有什么想法吗?

【问题讨论】:

    标签: mysql grafana


    【解决方案1】:

    使用一个查询来返回您想要的结果的所有值并左连接表以进行聚合:

    select t.reference, count(l.id) 
    from (
      select 'ref1' reference union all
      select 'ref2' union all
      select 'ref3' 
    ) t left join db.log l
    on l.reference = t.reference
    group by t.reference
    

    查看简化的demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 2012-07-23
      • 2015-01-25
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      • 2022-06-21
      相关资源
      最近更新 更多