简体   繁体   English

如何在postgres中将upvote和post表聚合在一起?

[英]How to aggregate upvote and post tables together in postgres?

I'm looking for a way to aggregate posts and the upvotes related to that post together using PostgreSQL.我正在寻找一种使用 PostgreSQL 将帖子和与该帖子相关的赞成票聚合在一起的方法。 I want to make it similar to reddit's upvote systems, where upvotes come already fetched and don't need to be loaded on client side.我想让它类似于 reddit 的 upvote 系统,其中 upvotes 已经获取并且不需要在客户端加载。

I have made these simple tables.我做了这些简单的表格。

upvotes.sql

CREATE TABLE upvotes (
    id BIGSERIAL NOT NULL PRIMARY KEY,
    post_id BIGINT NOT NULL REFERENCES posts(id)
    user_id BIGINT NOT NULL REFERENCES users(id)
);

users.sql

CREATE TABLE users (
    id BIGSERIAL NOT NULL PRIMARY KEY,
    name VARCHAR NOT NULL
);

posts.sql

CREATE TABLE posts (
    id BIGSERIAL NOT NULL PRIMARY KEY,
    content VARCHAR NOT NULL
)

Basically I want to make my response look something like this:基本上我想让我的回复看起来像这样:

post.json

{
    id: 1234,
    content: "foo",
    upvotes: 1234
}

Is there a way for doing this with a single query?有没有办法用一个查询来做到这一点? I feel like this is a simple question but don't really know how to make it work...我觉得这是一个简单的问题,但真的不知道如何使它起作用......

Here it is.这里是。

select to_jsonb(t.*)
from
(
  select p.id, p.content, count(*) upvotes_count
  from posts p 
  inner join upvotes uv on p.id = uv.post_id 
  group by p.id, p.contents
) t
-- where id = 1234;

Please note that if posts.id is primary key then p.contents is redundant in the group by clause.请注意,如果posts.id是主键,则p.contentsgroup by子句中是多余的。 We do not actually pay attention who are the users that upvoted the post but only how many they are.我们实际上并不关注谁是给帖子点赞的用户,而只关注他们有多少。 So table users is not used in the query.所以在查询中不使用表users

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM