как в подзапросе использовать данные из основного запроса в postgresql?
- User
как в подзапросе использовать данные из основного запроса в postgresql?
- Assistant
В PostgreSQL вы можете использовать данные из основного запроса в подзапросе с помощью оператора
WITH(также известного как Common Table Expressions, CTE) или вложенных запросов.Вот пример с использованием CTE:
WITH main_query AS ( SELECT id, name FROM your_table WHERE some_condition ) SELECT mq.id, mq.name, (SELECT COUNT(*) FROM another_table WHERE another_condition = mq.id) AS related_count FROM main_query mq;В этом случае мы сначала определяем основную выборку с помощью CTE, а затем используем данные из CTE (
mq) в подзапросе для расчетаrelated_count.Вы также можете использовать подзапрос непосредственно в основном запросе:
SELECT id, name, (SELECT COUNT(*) FROM another_table WHERE another_condition = your_table.id) AS related_count FROM your_table WHERE some_condition;В этом случае подзапрос использует
your_table.idдля вычисления значенияrelated_count.Оба подхода позволяют вам использовать данные из основного запроса в подзапросе. Выбор между ними зависит от конкретной задачи и личных предпочтений.
- User
Мне нужно в подзапросе использовать данные из основного запроса по периодам, вот запрос: select id , period_id , subject_id , indicator_kpi_sed , is_actual , summary , data_ownership , value , value_plan , color_difference_current_year , completion_percent , position , difference_rf , difference_fo , difference_current_year , higher_lower_rf , higher_lower_fo , position_rf , position_fo , dif_position_rf , dif_position_fo , score_rf , score_fo , color_value , color_cp , color_dif_position_rf , color_dif_position_fo , color_map from dblink ('planeta_arm_reg_srv', 'select pk_id, fk_period, fk_subject, fk_indicator_kpi_sed, fk_is_actual, fk_summary, fk_data_ownership, value, value_plan, colour_difference_current_year, completion_percent, position, difference_rf, difference_fo, difference_current_year, higher_lower_rf, higher_lower_fo, position_rf, position_fo, dif_position_rf, dif_position_fo, score_rf, score_fo, colour_value, colour_cp, colour_dif_position_rf, colour_dif_position_fo, colour_map from regions.f_kpi_sed where value is not null and fk_indicator_kpi_sed = ''7'' and fk_period in ( select distinct from )') as q ( id bigint, period_id bigint, subject_id bigint, indicator_kpi_sed bigint, is_actual bigint, summary bigint, data_ownership bigint, value numeric, value_plan numeric, color_difference_current_year integer, completion_percent numeric, position integer, difference_rf numeric, difference_fo numeric, difference_current_year numeric, higher_lower_rf integer, higher_lower_fo integer, position_rf integer, position_fo integer, dif_position_rf integer, dif_position_fo integer, score_rf numeric, score_fo numeric, color_value integer, color_cp integer, color_dif_position_rf integer, color_dif_position_fo integer, color_map integer)
- Assistant
В вашем запросе вы хотите использовать данные из основного запроса в подзапросе, который находится внутри функции
dblink. В частности, вы хотите получить уникальные значенияfk_periodиз основной выборки для фильтрации при использовании функции.Если вы планируете использовать подзапрос внутри
dblink, убедитесь, что подзапрос возвращает нужные значения. Вот как можно изменить ваш запрос, чтобы использовать данные из основного запроса для ограничения периодов. Однако, так какdblinkтребует, чтобы вся SQL-запрос выполнялся на удаленной стороне, вам нужно сформировать запрос с параметрами до вызоваdblink. Одним из способов реализации этого может быть использование динамической строки SQL.Представим, что у вас есть временная таблица или CTE, которая содержит необходимые значения
fk_period, и вы хотите передать их вdblink. Ниже представлен пример:-- Создайте временную таблицу или используйте CTE, чтобы получить уникальные периоды WITH unique_periods AS ( SELECT DISTINCT fk_period FROM your_local_table WHERE your_conditions ) SELECT id, period_id, subject_id, indicator_kpi_sed, is_actual, summary, data_ownership, value, value_plan, color_difference_current_year, completion_percent, position, difference_rf, difference_fo, difference_current_year, higher_lower_rf, higher_lower_fo, position_rf, position_fo, dif_position_rf, dif_position_fo, score_rf, score_fo, color_value, color_cp, color_dif_position_rf, color_dif_position_fo, color_map FROM dblink('planeta_arm_reg_srv', 'SELECT pk_id, fk_period, fk_subject, fk_indicator_kpi_sed, fk_is_actual, fk_summary, fk_data_ownership, value, value_plan, colour_difference_current_year, completion_percent, position, difference_rf, difference_fo, difference_current_year, higher_lower_rf, higher_lower_fo, position_rf, position_fo, dif_position_rf, dif_position_fo, score_rf, score_fo, colour_value, colour_cp, colour_dif_position_rf, colour_dif_position_fo, colour_map FROM regions.f_kpi_sed WHERE value IS NOT NULL AND fk_indicator_kpi_sed = ''7'' AND fk_period IN (' || (SELECT string_agg(DISTINCT fk_period::text, ',') FROM unique_periods) || '))') AS q ( id bigint, period_id bigint, subject_id bigint, indicator_kpi_sed bigint, is_actual bigint, summary bigint, data_ownership bigint, value numeric, value_plan numeric, color_difference_current_year integer, completion_percent numeric, position integer, difference_rf numeric, difference_fo numeric, difference_current_year numeric, higher_lower_rf integer, higher_lower_fo integer, position_rf integer, position_fo integer, dif_position_rf integer, dif_position_fo integer, score_rf numeric, score_fo numeric, color_value integer, color_cp integer, color_dif_position_rf integer, color_dif_position_fo integer, color_map integer);В этом примере:
- Мы создаем CTE
unique_periods, в котором находятся уникальные значенияfk_period. - Мы используем
string_aggдля создания строки с периодами, которая будет вставлена в запросdblink. - Значение
fk_periodформируется динамически и передается в запросdblink.
Обратите внимание на правильное экранирование кавычек внутри строки запроса к
dblink, чтобы избежать синтаксических ошибок. - Мы создаем CTE