Possible to use IF in a query?

拈花ヽ惹草 提交于 2021-02-11 12:47:14

问题


I'm using Grafana to plot data from a MySQL datasource. Is it possible to, in a panel's query editor, use an IF ... THEN ... type statement. I would like to create a variable that I could put in the IF. I want the variable to be a condition, not necessarily to be used directly in the query.

For example:

//IN THE DATA SOURCE:

CREATE TABLE Example (Id INT, ANIMALS VARCHAR(15));
INSERT INTO Example VALUES (1,'Dog'), (2,'Fish'), (3,'Cat'), (4,'Lizard')

For a variable Test with values "Mammal',"Reptile", "Other":

//WHAT I'D LIKE IN GRAFANA QUERY EDITOR:

IF($Test = "Mammal") THEN
SELECT * FROM Example WHERE Id = 1 OR Id =3;
ELSE
SELECT * FROM Example WHERE Id = 2 OR Id =4;
END IF;

Is this kind of condition based query even possible? If so, what is the proper syntax to get it to work? Is there any way I can use Grafana variables to have a similar effect?


回答1:


Use query. Query starts with SELECT keyword. Don't use any IF ELSE conditions before query, e.g.:

SELECT * 
FROM Example 
WHERE 
  Data IN ( ${variable:csv} )

This WHERE condition syntax will work with single value, multi value Grafana dashboard variables and also with All value (no custom All value, but blank=auto). Of course this condition is mainly for INT column types. STRING types may need different one (e.g. with LIKE and regexp matching).

Code all your logic (dependency on the dashboard variable) in the WHERE section. Use query inspector to see SQL which is generated and tweak it to correct SQL syntax.



来源:https://stackoverflow.com/questions/65303442/possible-to-use-if-in-a-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!