Grafana-如何为Mysql数据源创建sql查询部件变量/宏

时间:2019-01-25 06:41:29

标签: mysql grafana grafana-templating grafana-variable

我在Grafana中有以下查询,该查询由MySql DataSource支持。

SELECT
  $__timeGroupAlias(ts,$__interval),
  sum(total) AS "total"
FROM hp
WHERE
  $__timeFilter(ts) 
  AND customer_type IN ($CustomerType) AND age IN ($age) AND gender IN ($gender)
GROUP BY 1
ORDER BY $__timeGroup(ts,$__interval)

控制板上有多个singleStat / panel / graphs,它们使用不同的选择参数,但是WHERE条件在所有参数中都保持不变。

我想将条件保留为单独的常量变量,以便可以在每个查询中仅添加该变量。

我试图像这样建立查询。

SELECT
  $__timeGroupAlias(ts,$__interval),
  sum(total) AS "total"
FROM hp
$where_condition
GROUP BY 1
ORDER BY $__timeGroup(ts,$__interval)

,并将where_condition声明为WHERE $__timeFilter(ts) AND customer_type IN ($CustomerType) AND age IN ($age) AND gender IN ($gender)

但是查询失败,因为内部变量($ CustomerType,$ age,$ gender)未由查询生成器解析,并且生成的查询如下所示。

SELECT
  UNIX_TIMESTAMP(ts) DIV 900 * 900 AS "time",
  sum(total) AS "total"
FROM hp
ts BETWEEN FROM_UNIXTIME(1548311714) AND FROM_UNIXTIME(1548398114) 
AND customer_type IN ($CustomerType) AND age IN ($age) AND gender IN ($gender)
GROUP BY 1
ORDER BY UNIX_TIMESTAMP(ts) DIV 900 * 900

是否有一种方法可以解决其他变量中包含的变量。还是有其他方法可以外部化包含变量的查询部分?

2 个答案:

答案 0 :(得分:0)

constant变量类型仅生成静态字符串。它没有替代任何变量。切换为query类型,然后使用MySQL返回字符串,该字符串将具有您的where_condition变量的确切字符串值。查询:

SELECT 'WHERE $__timeFilter(ts) AND customer_type IN ($CustomerType) AND age IN ($age) AND gender IN ($gender)'

恕我直言:变量替换也应适用于constant类型。您可以为此https://github.com/grafana/grafana/issues打开功能请求。

答案 1 :(得分:0)

我在引号方面也遇到了问题,这是我的解决方案,支持“全部”和许多选定项:

SELECT '
task_run_table.is_system = false 
AND 
(
    ''__all__'' = ''${user:raw}''
    OR 
    task_run_table.user  = any ( string_to_array(''${user:raw}'', '','')::text[])
)
AND 
(
    ''__all__'' = ''${job:raw}''
    OR 
    task_run_table.job_name  = any ( string_to_array(''${job:raw}'', '','')::text[])
)
' 

All的值已覆盖为__all__。 这样使用:

SELECT 
  $__timeGroup(task_run_table.start_time, '$interval', NULL),
  task_run_table.name AS metric,
  COUNT(*) AS value
FROM
  task_run_table
WHERE 
  $__timeFilter(task_run_table.start_time) 
  AND 
  ${default_filter:raw}
  AND 
  task_run_table.state = $state
GROUP BY time, task_run_table.name
ORDER BY time, value DESC