我有2个主要表格 - posts
和users
,以及第三个表格,用于将用户喜欢的帖子存储为一行。我需要对与用户数据连接的帖子进行查询,以及当前用户是否有优惠帖子(在user_favs
表中查找)。
最终我想向客户返回类似以下的内容:
{
post_id: '...',
title: '...',
user_id: '...',
username: '...',
isFavourited: isFaved > 0 ? true : false
}
这可以用1个选择查询吗?
CREATE TABLE posts (
post_id uuid,
title text
author_id uuid
);
CREATE TABLE users (
user_id uuid,
username text
);
CREATE TABLE user_favs (
user_id uuid REFERENCES users ON DELETE CASCADE,
post_id uuid REFERENCES posts ON DELETE CASCADE
);
我的查询如下:
SELECT
p.post_id,
p.title,
u.user_id,
u.username,
count(f.*) as isfaved
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
LEFT JOIN user_favs f
ON f.user_id = p.author_id AND f.post_id = '1234'
我也尝试过:
SELECT
p.post_id,
p.title,
u.user_id,
u.username,
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
LEFT JOIN
(SELECT count(*) FROM user_favs
) f ON f.user_id = p.author_id AND f.post_id = '1234'
编辑:只是为了澄清我希望完成的事情:我提取帖子,返回该帖子的相应作者,然后还检查帖子是否被请求用户收藏。
答案 0 :(得分:0)
您可能最好将选择计数(*)放入SELECT子句中,类似于
SELECT
p.post_id,
p.title,
u.user_id,
u.username,
(SELECT count(*) FROM user_favs f where f.user_id = p.author_id AND f.post_id = p.post_id)
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
答案 1 :(得分:0)
我改变了表格以便我可以测试它。根据您提供的信息: 选择给定的帖子,帖子信息,作者以及当前用户(我猜的是已登录的用户)是否获得该帖子:
drop table if exists user_favs cascade;
drop table if exists posts cascade;
drop table if exists users cascade;
CREATE TABLE users (
user_id int primary key,
username text
);
CREATE TABLE posts (
post_id int primary key,
title text,
user_id int references users
);
CREATE TABLE user_favs (
user_id int REFERENCES users ON DELETE CASCADE,
post_id int REFERENCES posts ON DELETE CASCADE
);
SELECT
p.post_id,
p.title,
u.user_id,
u.username,
case when f.user_id is not null then true else false end as isfaved
FROM posts p
JOIN users u ON p.user_id = u.user_id
LEFT JOIN user_favs f on f.post_id = p.post_id
where p.post_id=1234 -- the post you want to select
and f.user_id = 4321; -- the id of the current user