PostgreSQL "likes" table 设计 - 按照递增 ID 的顺序选择是最优的吗?

PostgreSQL "likes" table design - selecting in order of incrementing ID is optimal?

我今天是 SQL 的新手,我正在设计一个鞋底 table,它将用于按顺序加载 post 之类的 [=15] =]一次。例如:为 post 加载前 10 个赞,稍后加载下 10 个,等等

我很好奇这种 table 设计和查询是否是最佳的? (所有其他数据都在 NoSQL 数据库中 ~ 不需要总点赞数)。

更具体地说; ORDER BY likeIDWHERE likeID > (starting point) 会减慢查询速度或使用不必要的资源吗? (likeID会自动递增,但有些点赞可能是table某个点的deleted/removed,这个table可能记录了百万个点赞。

postLikes table:

postID: string
userID: string
username: string
timestamp: int
likeID: uniqueID (int) - increments every like

用户加载前 2 个赞 post:

SELECT username, userID, likeID 
FROM postLikes 
WHERE (postID = “a1b767eae” AND likeID > 0)
ORDER BY likeID ASC 
LIMIT 2

returns:
[
   {username: "user6", userID: "SHi29s29", likeID: 324},
   {username: "user33", userID: "bsSU4s83", likeID: 1089}
]

然后用户加载下两个相同的点赞post:

...

WHERE (postID = “a1b767eae” AND likeID > 1089)
ORDER BY likeID ASC LIMIT 2

returns:
[
   {username: "user8", userID: "Bsh292he", likeID: 2934},
   {username: "user543", userID: "sjXks28S", likeID: 10354}
]

性能的关键因素是匹配 multicolumn index:

CREATE INDEX ON post_likes (post_id, like_id);

按此顺序使用索引列。参见:

如果 SELECT 列表中唯一的其他列是 username,请考虑覆盖索引(需要 Postgres 11 或更高版本),例如:

CREATE INDEX ON post_likes (post_id, like_id) INCLUDE (username);

并保持 table 真空以允许 index-only scans。参见:

  • Postgres not using index when index scan is much better option

哦,不要在 Postgres 中使用 CaMeL-case 标识符。参见:

  • Are PostgreSQL column names case-sensitive?