AlloyDB 인스턴스를 쿼리하는 데 필요한 권한을 얻으려면 관리자에게 프로젝트에 대한 BigQuery 연결 사용자(roles/bigquery.connectionUser) IAM 역할을 부여해 달라고 요청하세요.
역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.
고객 테이블은 BigQuery에, 판매 테이블은 AlloyDB에 저장되어 있는 상황에서 하나의 쿼리로 두 테이블을 조인하려는 경우가 있습니다. 다음 예시에서는 orders라는 AlloyDB 테이블에 통합 쿼리를 만들고 결과를 mydataset.customers라는 BigQuery 테이블과 조인합니다.
예시 쿼리는 다음과 같은 세 개의 부분으로 구성됩니다.
AlloyDB 데이터베이스에서 외부 쿼리 SELECT customer_id, MIN(order_date) AS
first_order_date FROM orders GROUP BY customer_id를 실행하여 EXTERNAL_QUERY 함수를 통해 각 고객의 첫 주문 날짜를 구합니다.
customer_id를 기준으로 BigQuery에서 외부 쿼리 결과 테이블을 고객 테이블과 조인합니다.
최종 결과 집합에서 고객 정보와 첫 주문 날짜를 선택합니다.
SELECTc.customer_id,c.name,rq.first_order_dateFROMmydataset.customersAScLEFTOUTERJOINEXTERNAL_QUERY('us.connection_id','''SELECT customer_id, MIN(order_date) AS first_order_date FROM orders GROUP BY customer_id''')ASrqONrq.customer_id=c.customer_idGROUPBYc.customer_id,c.name,rq.first_order_date;
AlloyDB 테이블 스키마 보기
EXTERNAL_QUERY 함수를 사용하여 information_schema 테이블을 쿼리하여 데이터베이스 메타데이터에 액세스할 수 있습니다. 예를 들어 데이터베이스의 모든 테이블을 나열하거나 테이블 스키마를 볼 수 있습니다. 자세한 내용은 PostgreSQL information_schema 테이블을 참조하세요.
-- List all tables in a database.SELECT*FROMEXTERNAL_QUERY("region.connection_id","select * from information_schema.tables;");
-- List all columns in a table.SELECT*FROMEXTERNAL_QUERY("region.connection_id","select * from information_schema.columns where table_name='x';");
BigQuery 통합 쿼리 추적
AlloyDB에 대해 통합 쿼리를 실행하면 BigQuery는 다음과 유사한 주석으로 쿼리에 주석을 추가합니다.
이 섹션에서는 통합 쿼리를 AlloyDB에 전송할 때 발생할 수 있는 잠재적 오류를 설명하고 가능한 문제 해결 방법을 제공합니다.
문제: 다음 오류로 데이터베이스 서버에 연결할 수 없음:
Invalid table-valued function EXTERNAL_QUERY Connect to PostgreSQL server failed: server closed the connection unexpectedly. This probably means the server terminated abnormally before or while processing the request.
해결 방법:AlloyDB에 대한 연결을 만드는 동안 유효한 사용자 인증 정보를 사용하고 모든 기본 요건을 따랐는지 확인합니다.
AlloyDB에 연결할 때 자동으로 생성되는 서비스 계정에 AlloyDB 클라이언트(roles/alloydb.client) 역할이 있는지 확인합니다.
자세한 내용은 서비스 계정에 액세스 권한 부여를 참조하세요.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-01-31(UTC)"],[],[],null,["# AlloyDB federated queries\n=========================\n\nAs a data analyst, you can query data in AlloyDB for PostgreSQL from BigQuery\nusing [federated queries](/bigquery/docs/federated-queries-intro).\n\nBigQuery AlloyDB federation lets BigQuery\nquery data residing in AlloyDB in real time without copying or\nmoving the data.\n\nBefore you begin\n----------------\n\n- Ensure that your BigQuery administrator has created an [AlloyDB connection](/bigquery/docs/connect-to-alloydb#create-alloydb-connection) and [shared](/bigquery/docs/connect-to-alloydb#share_connections) it with you.\n-\n\n To get the permissions that\n you need to query an AlloyDB instance,\n\n ask your administrator to grant you the\n\n\n [BigQuery Connection User](/iam/docs/roles-permissions/bigquery#bigquery.connectionUser) (`roles/bigquery.connectionUser`)\n IAM role on your project.\n\n\n For more information about granting roles, see [Manage access to projects, folders, and organizations](/iam/docs/granting-changing-revoking-access).\n\n\n You might also be able to get\n the required permissions through [custom\n roles](/iam/docs/creating-custom-roles) or other [predefined\n roles](/iam/docs/roles-overview#predefined).\n\nQuery data\n----------\n\nTo send a federated query to AlloyDB from a\nGoogleSQL query, use the\n[`EXTERNAL_QUERY` function](/bigquery/docs/reference/standard-sql/federated_query_functions#external_query).\n\nSuppose that you store a customer table in BigQuery, while\nstoring a sales table in AlloyDB, and want to join the two tables in\na single query. The following example makes a federated query to an\nAlloyDB table named `orders` and joins the results with a\nBigQuery table named `mydataset.customers`.\n\nThe example query includes 3 parts:\n\n1. Run the external query `SELECT customer_id, MIN(order_date) AS\n first_order_date FROM orders GROUP BY customer_id` in the AlloyDB database\n to get the first order date for each customer through\n the `EXTERNAL_QUERY` function.\n\n2. Join the external query results table with the customers table in\n BigQuery by `customer_id`.\n\n3. Select customer information and first order date in the final result set.\n\n SELECT c.customer_id, c.name, rq.first_order_date\n FROM mydataset.customers AS c\n LEFT OUTER JOIN EXTERNAL_QUERY(\n 'us.connection_id',\n '''SELECT customer_id, MIN(order_date) AS first_order_date\n FROM orders\n GROUP BY customer_id''') AS rq ON rq.customer_id = c.customer_id\n GROUP BY c.customer_id, c.name, rq.first_order_date;\n\nView an AlloyDB table schema\n----------------------------\n\nYou can use the `EXTERNAL_QUERY` function to query `information_schema` tables\nto access database metadata. For example, you can list all of the tables in the\ndatabase or view the table schema. For more information, see [PostgreSQL information_schema tables](https://www.postgresql.org/docs/9.1/information-schema.html). \n\n -- List all tables in a database.\n SELECT * FROM EXTERNAL_QUERY(\"region.connection_id\",\n \"select * from information_schema.tables;\");\n\n -- List all columns in a table.\n SELECT * FROM EXTERNAL_QUERY(\"region.connection_id\",\n \"select * from information_schema.columns where table_name='x';\");\n\nTrack BigQuery federated queries\n--------------------------------\n\nWhen you run a federated query against AlloyDB,\nBigQuery annotates the query with a comment similar to the following: \n\n```\n/* Federated query from BigQuery. Project ID: PROJECT_ID, BigQuery Job ID: JOB_ID. */\n```\n\nIf you are monitoring logs for query usage, the following annotation can help you\nidentify queries coming from BigQuery.\n\n1. Go to the **Logs Explorer** page.\n\n [Go to the Logs Explorer](https://console.cloud.google.com/logs/query)\n2. In the **Query** tab, enter the following query:\n\n resource.type=\"alloydb.googleapis.com/Instance\"\n textPayload=~\"Federated query from BigQuery\"\n\n3. Click **Run query**.\n\n If there are records available for BigQuery federated queries,\n a list of records similar to the following appears in **Query results**. \n\n ```\n YYYY-MM-DD hh:mm:ss.millis UTC [3210064]: [4-1]\n db=DATABASE, user=USER_ACCOUNT\n STATEMENT: SELECT 1 FROM (SELECT FROM company_name_table) t;\n /* Federated query from BigQuery.\n Project ID: PROJECT_ID, BigQuery Job ID: JOB_ID\n */\n\n YYYY-MM-DD hh:mm:ss.millis UTC [3210532]: [2-1]\n db=DATABASE, user=USER_ACCOUNT\n STATEMENT: SELECT \"company_id\", \"company type_id\" FROM\n (SELECT FROM company_name_table) t;\n /* Federated query from BigQuery.\n Project ID: PROJECT_ID, BigQuery Job ID: JOB_ID\n */\n ```\n\n For more information about Cloud Logging, see [Cloud Logging](/logging/docs/view/logs-explorer-interface).\n\nTroubleshooting\n---------------\n\nThis section describes potential errors you might encounter when sending a\nfederated query to AlloyDB and provides possible troubleshooting\nresolutions.\n\n**Issue:** Failed to connect to the database server with this error:\n`Invalid table-valued function EXTERNAL_QUERY Connect to PostgreSQL server failed: server closed the connection unexpectedly. This probably means the server terminated abnormally before or while processing the request.`\n\n**Resolution:** Ensure that you used valid credentials and followed all prerequisites\nwhile creating the [connection to AlloyDB](/bigquery/docs/connect-to-alloydb#create-alloydb-connection).\nCheck if the service account that is automatically created\nwhen a connection to AlloyDB is\ncreated has the AlloyDB Client (`roles/alloydb.client`) role.\nFor more information, see\n[Grant access to the service account](/bigquery/docs/connect-to-alloydb#access-alloydb).\n\nWhat's next\n-----------\n\n- Learn about [federated queries](/bigquery/docs/federated-queries-intro).\n- Learn about [PostgreSQL to BigQuery data type mapping](/bigquery/docs/reference/standard-sql/federated_query_functions#postgresql_mapping).\n- Learn about [unsupported data types](/bigquery/docs/reference/standard-sql/federated_query_functions#unsupported_data_types)."]]