我正在尋找一種使用 PostgreSQL 將帖子和與該帖子相關的贊成票聚合在一起的方法。我想讓它類似于 reddit 的 upvote 系統,其中 upvotes 已經獲取并且不需要在客戶端加載。
我做了這些簡單的表格。
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
)
基本上我想讓我的回復看起來像這樣:
post.json
{
id: 1234,
content: "foo",
upvotes: 1234
}
有沒有辦法用一個查詢來做到這一點?我覺得這是一個簡單的問題,但真的不知道如何使它起作用......
uj5u.com熱心網友回復:
這里是。
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;
請注意,如果posts.id是主鍵,則p.contents在group by子句中是多余的。我們實際上并不關注誰是給帖子點贊的用戶,而只關注他們有多少。所以users在查詢中不使用表。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/352985.html
標籤:sql PostgreSQL
