簡體   English   中英

UNION ALL 參數化查詢

[英]UNION ALL parameterised queries

我有一個工作正常的查詢。 問題是該查詢的一部分是需要從文件中讀取的字符串。 對每個字符串的查詢產生 6 個輸出。 我需要該文件的所有結果的聯合,以便最終結果是一個包含 6x 個字符串的表。 我可以使用 Python 讀取文件。

我已經嘗試過使用參數化查詢。 他們每個人只返回基於字符串的 6 行。

我的大部分 Python 代碼都基於此處的BigQuery 文檔。

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

請查看以下使用公共數據的示例(您也可以運行查詢)

#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),
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM