python - UNION ALL 参数化查询

标签 python sql google-bigquery

我有一个运行良好的特定查询。问题在于该查询的一部分是需要从文件中读取的字符串。对每个字符串的查询会产生 6 个输出。我需要该文件的所有结果的并集,以便最终结果是一个包含 6 倍字符串的表。我可以使用 Python 读取该文件。

我已经尝试过使用参数化查询。它们每个都只根据字符串返回 6 行。

我的大部分 Python 代码都基于 BigQuery 的文档 here .

query = """
    SELECT pet_id, age, name
    FROM `myproject.mydataset.mytable`
    WHERE name = @name
    AND species = @species;
"""
query_params = [
    bigquery.ScalarQueryParameter('name', 'STRING', 'Max'),
    bigquery.ScalarQueryParameter('species', 'INT64', 'Dog'), 
    bigquery.ScalarQueryParameter('name', 'STRING', 'Alfred'), 
    bigquery.ScalarQueryParameter('species', 'INT64', 'Cat')
]
job_config = bigquery.QueryJobConfig()
job_config.query_parameters = query_params
query_job = client.query(
    query,
    # Location must match that of the dataset(s) referenced in the query.
    location='US',
    job_config=job_config)  # API request - starts the query

# Print the results
for row in query_job:
    print('{}: \t{}'.format(row.word, row.word_count))

如何获得许多这些查询结果的 UNION ALL?

输出应该如下所示

pet_id | age | name
___________________
1      | 5   | Max
2      | 8   | Alfred

最佳答案

请查看下面使用公共(public)数据的示例(您也可以运行查询)

#standardSQL
SELECT * 
FROM `bigquery-public-data.baseball.schedules`
WHERE (year, duration_minutes) IN UNNEST([(2016, 187), (2016, 165), (2016, 189)])

这里的关键是您提供一个要用来过滤表的值数组,并使用 IN UNNEST(array_of_values) 来完成这项工作,最好如下所示:

query = """
    SELECT pet_id, age, name
    FROM `myproject.mydataset.mytable`
    WHERE (name, species) IN UNNEST(@filter_array);
"""

有点不幸的是,BigQuery Python API 不允许您指定 array< struct<string, int64> >作为查询参数。所以你可能需要这样做:

query = """
    SELECT pet_id, age, name
    FROM `myproject.mydataset.mytable`
    WHERE concat(name, "_", species) IN UNNEST(@filter_array);
"""
array_of_pre_concatenated_name_and_species = ['Max_Dog', 'Alfred_Cat']
query_params = [
    bigquery.ArrayQueryParameter('filter_array', 'STRING', array_of_pre_concatenated_name_and_species),
]

关于python - UNION ALL 参数化查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55482811/

相关文章:

python - 从 python 中的包中获取模块名称

python - 如何并行遍历两个列表?

mysql - 稍微复杂一点的多对多关系

google-bigquery - 用条件滞后语句查询

google-bigquery - 将一张表附加到另一张表

python - Django:从批处理/cron 脚本记录

Python 不求和(添加)数字,只是将它们粘在一起

java - 编译时: Creation table error

c# - 如何在 NHibernate 中使用子查询作为联接?

sql - 使用带有 DISTINCT 的 ARRAY_AGG() 和带有 ORDINAL 的 ORDER BY