我需要编写一个postgres查询来获取beta_plan_id的集群ID并稍后进行一些操作..对于下表中的单个beta_plan_id,可能有许多merch id和很多cluster_id。这将如何处理??
BETA_PLAN_ID MERCH_LEVEL1_ID BETA_PLAN_MERCH_LVL1_CLSTR_ID NO_OF_STORES
1 1 12 5,6,7
1 1 13 9,10
1 1 14 2,3,4
2 2 15 13,12
SELECT BETA_PLAN_MERCH_LVL1_CLSTR_ID INTO i_clstr_id
FROM beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR
WHERE BETA_PLAN_ID = in_beta_plan_id;
问题是将返回许多结果,因为BETA_PLAN_MERCH_LVL1_CLSTR_ID是一个串行类型,并且为(beta_plan_id,merch_id,cluster_id)组合唯一生成。
SELECT BETA_PLAN_MERCH_LVL1_CLSTR_ID
INTO i_clstr_id
FROM beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR
WHERE BETA_PLAN_ID = in_beta_plan_id;
INSERT INTO beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR
(
BETA_PLAN_ID,
MERCH_LEVEL1_ID,
CLUSTER_ID,
CLUSTER_NAME,
NO_OF_STORES,
NO_OF_FOOTAGE_VARIATION,
CREATED_USER,
CREATED_TS
)
SELECT
out_plan_id,
merch_lvl1_clstr.MERCH_LEVEL1_ID,
merch_lvl1_clstr.CLUSTER_ID,
merch_lvl1_clstr.CLUSTER_NAME,
merch_lvl1_clstr.NO_OF_STORES,
merch_lvl1_clstr.NO_OF_FOOTAGE_VARIATION
in_user_id,
now()
FROM beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR merch_lvl1_clstr
INNER JOIN beta_plan.BETA_PLAN_MERCH_COPY_PLAN merch_copy
ON merch_copy.MERCH_ID = merch_lvl1_clstr.MERCH_LEVEL1_ID
AND merch_lvl1_clstr.BETA_PLAN_ID = in_beta_plan_id
RETURNING BETA_PLAN_MERCH_LVL1_CLSTR_ID INTO o_clstr_id;
INSERT INTO beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR_STR
(
BETA_PLAN_MERCH_LVL1_CLSTR_ID,
STORE_ID,
CREATED_USER,
CREATED_TS
)
SELECT
o_clstr_id,
STORE_ID,
in_user_id,
now()
FROM beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR_STR
WHERE BETA_PLAN_MERCH_LVL1_CLSTR_ID = i_clstr_id;
答案 0 :(得分:0)
使用包含其他语句的SELECT
循环代替第一个FOR
语句:
FOR i_clstr_id IN
SELECT BETA_PLAN_MERCH_LVL1_CLSTR_ID
FROM beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR
WHERE BETA_PLAN_ID = in_beta_plan_id
LOOP
/* your two INSERT statements come here */
END LOOP;
有关详细信息,请参阅the documentation。