[英]POSTGRES sequence TRIGGER on non primary key
我有PostgreSQL數據庫9.5.0版。
表UserComments
創建如下:
create table UserComments (
userId integer,
commentNr integer,
comment text,
UNIQUE (userId, commentNr)
);
該表無法更改,我也不能添加額外的表。
我想根據userId
條目的數量對commentNr
進行排序(換句話說:自動遞增的值)。 對於具有相同userId
每個新條目,其值應增加。
例:
userId | commentNr | comment -------|-----------|--------- 1 | 1 | blabla 1 | 2 | more bla 2 | 1 | myownbla 1 | 3 | evenmorebla
我已經找到了一些有關“觸發器”和“窗口函數”的答案,但由於我不允許更改表,因此沒有一個對我真正有用。 最好的解決方案是在每個INSERT
上自動counts
/計算commentNr
因此我可以使用
insert into user(userId, comment) values ('1', 'bla');
任何幫助,將不勝感激。
對於這種簡單情況,沒有必要創建觸發器。 可以在CTE或子查詢中計算並插入正確的序列。
注意:如果使用下面的sql,則必須指定兩次插入的userId
INSERT INTO "user" ("userId", "commentNr", "comment") (
WITH
nextval AS (
SELECT COALESCE(MAX("commentNr"),0)+1 commentNr
FROM "user"
WHERE "userId" = '1'
)
SELECT '1', nextval.commentNr, 'bla'
FROM nextval
);
要自動計算commentNr字段,可以使用TRIGGER:
CREATE INDEX i1 ON UserComments (userId, commentNr DESC);
CREATE OR REPLACE FUNCTION set_commentNr() RETURNS TRIGGER AS $sql$
BEGIN
NEW.commentNr = coalesce(max(commentNr) + 1, 1) FROM UserComments WHERE UserId = NEW.userID;
RETURN NEW;
END;
$sql$ LANGUAGE plpgsql STABLE;
CREATE TRIGGER ins_comment BEFORE INSERT ON UserComments FOR EACH ROW EXECUTE PROCEDURE set_commentNr();
小測試:
insert into userComments (userId, comment) values ('1', 'bla');
insert into userComments (userId, comment) values ('1', 'bla');
insert into userComments (userId, comment) values ('2', 'bla');
insert into userComments (userId, comment) values ('1', 'bla');
insert into userComments (userId, comment) values ('2', 'bla');
SELECT * FROM userComments;
userid | commentnr | comment
--------+-----------+---------
1 | 1 | bla
1 | 2 | bla
2 | 1 | bla
1 | 3 | bla
2 | 2 | bla
(5 rows)
創建索引i1以提高計算下一個值的性能:
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------
Result (cost=4.17..4.18 rows=1 width=4) (actual time=0.032..0.032 rows=1 loops=1)
InitPlan 1 (returns $0)
-> Limit (cost=0.15..4.17 rows=1 width=4) (actual time=0.026..0.026 rows=1 loops=1)
-> Index Only Scan using i1 on usercomments (cost=0.15..24.27 rows=6 width=4) (actual time=0.021..0.021 rows=1 loops=1)
Index Cond: ((userid = 1) AND (commentnr IS NOT NULL))
Heap Fetches: 1
Planning time: 0.238 ms
Execution time: 0.095 ms
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.