简体   繁体   English

bigquery python API 中的查询可以使用 python 变量吗?

[英]Can queries in the bigquery python API use python variables?

I want to run a sql query on multiple tables in a dataset in bigquery.我想在 bigquery 的数据集中对多个表运行 sql 查询。 I have the names of these tables in a list in my python script and I want to loop through that list and run the query on every table in the list.我在 python 脚本的列表中有这些表的名称,我想遍历该列表并在列表中的每个表上运行查询。

My issue is that I cannot figure out how to structure my query to take python variables as inputs.我的问题是我无法弄清楚如何构造我的查询以将 python 变量作为输入。 For example, I have these variables in my script:例如,我的脚本中有这些变量:

# Variables for testing
dataset_id = 'test_dataset'
table_id = 'test_table'

This is how I'm trying to use them in my query object:这就是我尝试在查询 object 中使用它们的方式:

query = """
          SELECT *
          FROM """ + dataset_id + '.' + table_id + """
          ORDER BY 1 asc;

    """

This doesn't work and I can't find anything relevant on this online.这不起作用,我在网上找不到任何相关的东西。 I'd really appreciate it if you could help me structure this query correctly!如果您能帮助我正确构建此查询,我将不胜感激!

It should be working.它应该工作。 Just to be sure it's working, you can add backticks to the beginning and ending of the table name.为了确保它正常工作,您可以在表名的开头和结尾添加反引号。 Also, by using f-strings in python, you can inject variables in the strings in a more readable way.此外,通过在 python 中使用 f 字符串,您可以以更易读的方式在字符串中注入变量。

query = f"""
          SELECT *
          FROM `{dataset_id}.{table_id}`
          ORDER BY 1 asc;

    """

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM