What’s this for?
Variables in native queries let you dynamically replace values in your queries using filter widgets or through the URL.
本机查询中的变量允许您使用过滤器小部件或通过 URL 动态替换查询中的值。
Variables
{{variable_name}} creates a variable in this query template called “variable_name”. Variables can be given types in the side panel, which changes their behavior. All variable types other than “Field Filter” will automatically cause a filter widget to be placed on this question; with Field Filters, this is optional. When this filter widget is filled in, that value replaces the variable in the query template.
{{variable_name}} 在此查询模板中创建一个名为“variable_name”的变量。可以在侧面板中为变量指定类型,这会改变它们的行为。除“字段过滤器”之外的所有变量类型都会自动导致在此问题上放置过滤器小部件;对于字段过滤器,这是可选的。填充此过滤器小部件后,该值将替换查询模板中的变量。
Example:
SELECT count(*)
FROM products
WHERE category = {{category}}
Field Filters
Giving a variable the “Field Filter” type allows you to link questions to dashboard filter widgets or use more types of filter widgets on your SQL question. A Field Filter variable inserts SQL similar to that generated by the GUI query builder when adding filters on existing columns.
为变量提供“字段过滤器”类型允许您将问题链接到仪表板过滤器小部件或在 SQL 问题上使用更多类型的过滤器小部件。字段过滤器变量插入的 SQL 类似于在现有列上添加过滤器时由 GUI 查询生成器生成的 SQL。
When adding a Field Filter variable, you’ll need to map it to a specific field. You can then choose to display a filter widget on your question, but even if you don’t, you can now map your Field Filter variable to a dashboard filter when adding this question to a dashboard. Field Filters should be used inside of a “WHERE” clause.
添加字段过滤器变量时,您需要将其映射到特定字段。然后,您可以选择在您的问题上显示过滤器小部件,但即使不这样做,您现在也可以在将此问题添加到仪表板时将字段过滤器变量映射到仪表板过滤器。字段过滤器应该在“WHERE”子句内部使用。
Example:
SELECT count(*)
FROM products
WHERE {{created_at}}
Optional Clauses
Brackets around a [[{{variable}}]] create an optional clause in the template. If “variable” is set, then the entire clause is placed into the template. If not, then the entire clause is ignored.
[[{{variable}}]] 周围的括号在模板中创建一个可选子句。如果设置了“变量”,则整个子句都会放入模板中。如果不是,则忽略整个子句。
Example:
SELECT count(*)
FROM products
[[WHERE category = {{category}}]]
To use multiple optional clauses you can include at least one non-optional WHERE clause followed by optional clauses starting with “AND”.
要使用多个可选子句,您可以包含至少一个非可选 WHERE 子句,后跟以“AND”开头的可选子句
Example:
SELECT count(*)
FROM products
WHERE 1=1[[AND id = {{id}}]][[AND category = {{category}}]]
When using a Field Filter, the column name should not be included in the SQL. Instead, the variable should be mapped to a field in the side panel.
使用字段过滤器时,列名不应包含在 SQL 中。相反,变量应该映射到侧面板中的字段。
Example:
SELECT count(*)
FROM products
WHERE 1=1[[AND {{category}}]]