小编Rob*_*sen的帖子

如何根据行数执行条件插入?

我正在使用 Postgres 9.3,我需要根据表中已有的特定行数来防止插入到表中。这是表:

                                      Table "public.team_joins"
     Column      |           Type           |                            Modifiers                             
-----------------+--------------------------+---------------------------------------------------------
 id              | integer                  | not null default nextval('team_joins_id_seq'::regclass)
 team_id         | integer                  | not null
Indexes:
    "team_joins_pkey" PRIMARY KEY, btree (id)
    "team_joins_team_id" btree (team_id)
Foreign-key constraints:
    "team_id_refs_teams_id" FOREIGN KEY (team_id) REFERENCES teams(id) DEFERRABLE INITIALLY DEFERRED
Run Code Online (Sandbox Code Playgroud)

因此,例如,如果一个 id 为 3 的团队只允许 20 名玩家,并且SELECT COUNT(*) FROM team_joins WHERE team_id = 3等于 20,那么没有玩家应该能够加入团队 3。处理这种情况并避免并发问题的最佳方法是什么?我应该使用SERIALIZABLE事务来插入,还是可以WHERE在插入语句中使用这样的子句?

INSERT INTO team_joins (team_id)
VALUES (3)
WHERE (
  SELECT COUNT(*) FROM team_joins WHERE …
Run Code Online (Sandbox Code Playgroud)

postgresql database-design insert concurrency

9
推荐指数
1
解决办法
2万
查看次数

PostgreSQL 从 9.3 升级到 9.4 后非常慢

我们最近将一个 Amazon RDS 实例从 PostgreSQL 9.3 升级到 9.4。升级过程中没有出现问题,之后我们就跑了VACUUM ANALYZE。性能现在非常缓慢。下面是一个在 9.3 中花费几分之一秒的查询示例:

EXPLAIN ANALYZE SELECT room_name, id FROM common_activityinstance WHERE started_by_id = 1370408 AND room_name IN ('robcv28', 'foobartest', 'noroster', 'jscode', 'cv28', 'johansencouple', 'lv426', 'johansenfamily', 'johansen') AND end_time IS NULL;
                                                                              QUERY PLAN                                                                              
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on common_activityinstance  (cost=55.63..59.65 rows=1 width=13) (actual time=1.082..1.082 rows=0 loops=1)
   Recheck Cond: ((started_by_id = 1370408) AND (room_name = ANY ('{robcv28,foobartest,noroster,jscode,cv28,johansencouple,lv426,johansenfamily,johansen}'::text[])))
   Filter: (end_time IS NULL)
   Rows Removed by Filter: 925
   ->  BitmapAnd  (cost=55.63..55.63 rows=1 width=0) (actual …
Run Code Online (Sandbox Code Playgroud)

postgresql performance upgrade postgresql-9.3 postgresql-9.4 postgresql-performance

5
推荐指数
1
解决办法
1794
查看次数