我試圖運行PSQL下面的查詢 -PSQL「BEGIN TRANSACTION」語句錯誤
DO $$
BEGIN TRANSACTION
LOCK TABLE tags IN EXCLUSIVE MODE;
IF (SELECT COUNT(*)
FROM tags
WHERE user_id = 1) > 3
THEN
INSERT INTO "tags" ("user_id", "friend_id", "status", "explanation", "score", "created_at", "updated_at")
VALUES (1, 4, 'pending', '', 0.0, '2016-02-29 00:43:58.969313', '2016-02-29 00:43:58.969313')
RETURNING "id";
INSERT INTO "tags" ("user_id", "friend_id", "status", "explanation", "score", "created_at", "updated_at")
VALUES (4, 1, 'pending', '', 0.0, '2016-02-29 00:43:58.969313', '2016-02-29 00:43:58.969313')
RETURNING "id";
ELSE
ROLLBACK;
END IF;
COMMIT;
$$;
不幸的是它不斷示數出有 -
ERROR: syntax error at or near "TRANSACTION"
LINE 2: BEGIN TRANSACTION
^
,我似乎無法到弄清楚爲什麼它不喜歡BEGIN TRANSACTION
。我嘗試添加;
並刪除關鍵字TRANSACTION
。
謝謝。這背景是有幾十個並行進程同時運行。 'LOCK TABLES'是這個的關鍵部分,所以每個進程在執行它的INSERT操作時簡要地鎖定表,這最終防止了雙重寫入。基於此,我仍然可以插入'LOCK TABLE匹配IN EXCLUSIVE MODE;'?我不認爲它默認鎖定表 – user2490003