我有三张表格,其结构如下:
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
username VARCHAR(255) UNIQUE
);
CREATE TABLE posts (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT REFERENCES users(id) NOT NULL,
category BIGINT REFERENCES categories(id) NOT NULL,
text TEXT NOT NULL
);
CREATE TABLE posts_votes (
user_id BIGINT REFERENCES users(id) NOT NULL,
post_id BIGINT REFERENCES posts(id) NOT NULL
value SMALLINT NOT NULL,
PRIMARY KEY(user_id, post_id)
);
我能够使用以下查询撰写一个查询,使用其用户及其总值获取每个帖子:
SELECT p.id, p.text, u.username, COALESCE(SUM(v.value), 0) AS vote_value
FROM posts p
LEFT JOIN posts_votes v ON p.id=t.post_id
JOIN users u ON p.user_id=u.id
WHERE posts.category=1337
GROUP BY p.id, p.text, u.username
但是现在我还想在上面的查询中返回一个为每个post_id SELECT COALESCE((SELECT value FROM posts_votes WHERE user_id=1234 AND post_id=n), 0)
返回n
结果的列。最好的方法是什么?
答案 0 :(得分:1)
我认为额外的.closest
是一种合理的方法:
LEFT JOIN