在Bigquery中使用Python API创建一个表并查询该表的值

问题描述 投票:0回答:1

我想创建一个新表并通过编写查询来分配该表的值。

from google.cloud import bigquery

bigquery_client = bigquery.Client(project="myproject")
dataset = bigquery_client.dataset("mydataset")
table_ref = dataset.table('New table')
table = bigquery.Table(table_ref)
table = client.create_table(table)

所以,我创建了一个空表

现在我希望从另一个名为“Old Table”的表中获得该表的一些值:

query = "SELECT * FROM `{Old table}`"

如何确保我的表链接到此查询?

我试过了

table.view_query = "SELECT * FROM `{Old table}`" 

但它不起作用

谢谢,

python google-bigquery
1个回答
1
投票

我认为你应该像这样使用smth:

bigquery_client = bigquery.Client(project="myproject")
dataset = bigquery_client.dataset("mydataset")
table_ref = dataset.table('New_table')

sql_query = "SELECT * FROM `{project}.{dataset}.{table}`"

job_config = bigquery.QueryJobConfig()

# Set configuration.query.destinationTable
job_config.destination = table_ref

# Set configuration.query.createDisposition
job_config.create_disposition = 'CREATE_IF_NEEDED'

# Set configuration.query.writeDisposition
job_config.write_disposition = 'WRITE_APPEND'

# Start the query
job = bigquery_client.query(sql_query, job_config=job_config)

# Wait for the query to finish
job.result()
© www.soinside.com 2019 - 2024. All rights reserved.