for 循环中的 DBT 引用

DBT ref within a for loop

我的 dbt 项目 ["base","table_1", "table_2", "table_3"...].

我想将它们全部加入一个公共列 id。

我想通过使用 for 循环宏来避免重复。我的问题是,当我尝试在 {{ref}} 中引用子查询名称 {{sub}} 时出现语法错误。

这是我正在尝试的代码。

{% set subs = ["table_1", "table_2", "table_3"] %}


SELECT
{% for sub in subs %}
    {{sub}}.* EXCEPT (id),
{% endfor %}
base.*
FROM {{ref('base')}} as base
{% for sub in subs %}
    LEFT JOIN {{ref({{sub}})}} as {{sub}}
    ON {{sub}}.id = base.id
{% endfor %}

我收到语法错误

expected token ':', got '}'

如果我改成

LEFT JOIN {{ref("'"{{sub}}"'")}} as {{sub}}

我收到这个错误

expected token ',', got '{'

终于有了

LEFT JOIN {{ref("{{sub}}")}} as {{sub}}

我明白了

Model depends on a node named '{{sub}}' which was not found

这是我阅读的一些页面,但看不到解决方案

https://docs.getdbt.com/reference/dbt-jinja-functions/ref

当您使用 ref() 时,您已经在表达式子句 ({{..}}) 中,因此您不需要添加另一个表达式子句来引用您的子句。

{% set subs = ["table_1", "table_2", "table_3"] %}


SELECT
{% for sub in subs %}
    {{sub}}.* EXCEPT (id),
{% endfor %}
base.*
FROM {{ref('base')}} as base
{% for sub in subs %}
    LEFT JOIN {{ ref(sub) }} as {{sub}}
    ON {{sub}}.id = base.id
{% endfor %}

但是,如果您的子查询确实是在同一模型中使用 with sql 子句的子查询,则不需要使用 ref(),因为它们不是数据库模型。您可以查看文档以更好地理解 ref()

{% set subs = ["table_1", "table_2", "table_3"] %}


SELECT
{% for sub in subs %}
    {{sub}}.* EXCEPT (id),
{% endfor %}
base.*
FROM {{ref('base')}} as base
{% for sub in subs %}
    LEFT JOIN {{ sub }}
    ON {{sub}}.id = base.id
{% endfor %}