I have following query in Grafana which is backed by 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)
There are multiple singleStat/panel/graphs in the Dashboard which use different select parameters but the WHERE condition remains same in all of them.
I want to keep the condition as separate constant variable so that I can add just that variable in every query.
I tried to build my query like this.
SELECT
$__timeGroupAlias(ts,$__interval),
sum(total) AS "total"
FROM hp
$where_condition
GROUP BY 1
ORDER BY $__timeGroup(ts,$__interval)
and declared where_condition
as WHERE $__timeFilter(ts) AND customer_type IN ($CustomerType) AND age IN ($age) AND gender IN ($gender)
.
But the query fails, because the internal variables ($CustomerType,$age,$gender) are not resolved by query generator and generated query looks like this.
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
Is there a way to resolve the variables which are contained in other variables. Or Is there any other way to externalise part of query which contains variables?
constant
variable type generates only static string. It didn't substitute any variables. Switch to query
type and use MySQL to return string, which will have exact string value for your where_condition
variable. Query:
SELECT 'WHERE $__timeFilter(ts) AND customer_type IN ($CustomerType) AND age IN ($age) AND gender IN ($gender)'
IMHO: variable substitution should works also for constant
type. You can open feature request for that https://github.com/grafana/grafana/issues.