我有3个表,需要从1-st中选择记录然后将记录插入到2-nd,最后将记录插入到3-rd
CREATE TABLE public.t_sender (
id BIGINT PRIMARY KEY NOT NULL DEFAULT nextval('t_sender_id_seq'::regclass),
soft_id SMALLINT NOT NULL,
sender_model_id SMALLINT NOT NULL,
);
CREATE TABLE public.t_receiver (
id BIGINT PRIMARY KEY NOT NULL DEFAULT nextval('t_receiver_id_seq'::regclass),
receiver_owner_id BIGINT,
);
CREATE TABLE public.t_sender_to_receiver (
id BIGINT PRIMARY KEY NOT NULL DEFAULT nextval('t_sender_to_receiver_id_seq'::regclass),
sender_id BIGINT NOT NULL,
receiver_id BIGINT NOT NULL,
FOREIGN KEY (sender_id) REFERENCES public.t_sender (id)
MATCH SIMPLE ON UPDATE RESTRICT ON DELETE RESTRICT,
FOREIGN KEY (receiver_id) REFERENCES public.t_receiver (id)
MATCH SIMPLE ON UPDATE RESTRICT ON DELETE RESTRICT
);
我从第一张表中获取了ID值
CREATE OR REPLACE FUNCTION selectreceiverWithoutsender(user_id_param bigint)
RETURNS setof bigint AS $BODY$
SELECT id FROM t_receiver WHERE id in (SELECT receiver_id FROM t_user_to_receiver WHERE user_id_param=$1) AND id NOT IN (SELECT receiver_id FROM t_sender_to_receiver);
$BODY$ LANGUAGE plpgsql;
然后插入第2和第3个表
CREATE OR REPLACE FUNCTION insertSendersForUserId(user_id_param bigint)
RETURNS void AS $BODY$
BEGIN
WITH insSender AS (insert into t_sender(sender_status, soft_id) select 1,0 from selectReceiverWithoutSender($1) RETURNING id)
INSERT INTO t_sender_to_receiver(receiver_id, sender_id) VALUES ((selectReceiverWithoutSender($1)), (select id from insSender) );
END;
$BODY$ LANGUAGE plpgsql;
我的问题是我从第一个插入 insSender 中获取了多个ID值,并在我尝试执行功能时出现下一个错误:
DO $$
BEGIN
select 1 from insertDadsForUserId(44);
END
$$ LANGUAGE plpgsql;
由用作表达式的子查询返回的多行 SQL状态:21000 上下文:SQL语句" WITH insSender AS(插入到t_sender ...
那么如何准备这个值以插入下一个插入?
对不起,如果这不是一个非常困难的问题,我第一次体验了PostgresSQL的功能,并没有在互联网上提供解决方案。