我创建了以下表格:
CREATE TABLE IF NOT EXISTS public.teams (
id SERIAL PRIMARY KEY,
name VARCHAR(64) NOT NULL UNIQUE
) WITH (OIDS = FALSE);
CREATE TABLE IF NOT EXISTS public.submissions (
id SERIAL PRIMARY KEY,
team_id INTEGER REFERENCES public.teams NOT NULL,
records_num INTEGER NOT NULL,
timestamp TIMESTAMP NOT NULL
) WITH (OIDS = FALSE);
CREATE TABLE IF NOT EXISTS public.predictions (
id SERIAL PRIMARY KEY,
submission_id INTEGER REFERENCES public.submissions NOT NULL,
customer INTEGER REFERENCES public.real NOT NULL,
date DATE NOT NULL,
billing NUMERIC(20, 2) NOT NULL
) WITH (OIDS = FALSE);
CREATE TABLE IF NOT EXISTS public.real (
customer INTEGER PRIMARY KEY,
date DATE NOT NULL,
billing NUMERIC(20, 2) NOT NULL
) WITH (OIDS = FALSE);
提交预测的关系是一对多;用户将以1000行的数据包提交预测,这些数据包应获得相同的提交id。
我正在尝试创建一个触发器,该触发器在创建提交行的预测上插入之前运行。这就是我目前所拥有的:
CREATE OR REPLACE FUNCTION insert_submission() RETURNS TRIGGER AS
$$
BEGIN
INSERT INTO submissions(team_id, records_num, timestamp)
VALUES (1, 1, '2018-04-21 00:00:00'); /*example values, need to fill with dynamically assigned ones, specially for records_num and team_id*/
RETURN NULL;
END
$$ LANGUAGE plpgsql;
DROP TRIGGER trigger_submission ON public.predictions;
CREATE TRIGGER trigger_submission BEFORE INSERT ON predictions
EXECUTE PROCEDURE insert_submission();
所以,我的问题是:
如何检索触发器插入的行的新创建submissions.id,以便将其添加到用户在预测中插入的所有行中?在插入之后,我需要运行另一个触发器吗?
编辑:要澄清以下@bignose答案,事件的顺序如下:
用户在public.predictions中插入1000行:
INSERT INTO predictions(customer, date, billing)
VALUES
(1, '2018-01-05', 543.42),
(4, '2018-04-02', 553.21),
...
(423, '2019-11-18', 38.87) /* 1000th row */
他不知道在这些行中插入哪一个SudiStudioID,并且实际上,这个预测包的提交行不存在,所以在一个触发器之前运行一个触发器来创建一个行来执行这样的事情:
INSERT INTO public.submisssions(team_id, records_num, timestamp)
VALUES (
4, /* I will need something to retrieve team_id here */
1000, /* I will need something to count the rows of the insert that triggered this */
NOW() /* convert to timestamp */
)
最后一个查询应返回刚刚创建的public.submission.id值,以插入用户请求的内容,从而使其最终如下所示:
INSERT INTO predictions(customer, date, billing)
VALUES
(@submission_id, 1, '2018-01-05', 543.42),
(@submission_id, 4, '2018-04-02', 553.21),
...
(@submission_id, 423, '2019-11-18', 38.87) /* 1000th row */
其中@submission\u id应该是从触发器中检索到的值(以及1000行中的一些值)
如何计算用户插入的行,以将其用作submissions.records_num的值?
假设我事先知道team.name,那么如何检索要在触发器执行期间插入的team.id?
谢谢您!
亲切的问候
最佳答案
一种触发器函数,用于行级触发器时,has access to the old and new state of the table。
CREATE OR REPLACE FUNCTION insert_submission() RETURNS TRIGGER AS
$$
BEGIN
INSERT INTO submissions(team_id, records_num, timestamp)
VALUES (NEW.foo, NEW.bar, '2018-04-21 00:00:00');
RETURN NULL;
END
$$ LANGUAGE plpgsql;
从描述中不清楚您希望从触发此函数的行中检索哪些字段。所以您需要用
NEW.foo
行状态的字段引用替换NEW.bar
和NEW
。关于sql - 触发创建父元素并在Postgresql中检索ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55111821/