[英]Inner join two tables and join count from a third table
我有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'
编辑:只是为了澄清我希望完成的工作:我正在获取一个帖子,返回该帖子的各自作者,然后还要检查该帖子是否受到请求用户的喜爱。
您最好将select count(*)放入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'
我改变了桌子,所以我可以测试它。 使用您提供的信息:为给定帖子选择帖子信息,作者以及当前用户(我猜为登录用户)是否偏爱该帖子:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.