小编典典

多对多关系,以确定用户是否喜欢某个帖子

sql

我有一个包含所有帖子的表。我还有一个表,当用户喜欢带有外键user_id和post_id的帖子时,会在其中添加一行。

我想检索 所有
帖子的列表,以及特定用户是否喜欢该帖子。使用外部联接,我最终两次获得一些帖子。用户1一次,用户2一次。如果我使用WHERE筛选likes.user_id =
1且likes.user_id为NULL,则不会得到仅被其他用户喜欢的帖子。

理想情况下,我将使用单个查询来执行此操作。SQL不是我的强项,所以我甚至不确定是否需要子查询或联接是否足够。

抱歉,我含糊其词,但我认为这是一个足够普遍的查询,应该有一定道理。

编辑:我用我提到的两个查询创建了一个数据库提琴。https://www.db-
fiddle.com/f/oFM2zWsR9WFKTPJA16U1Tz/4

更新:昨晚想通了。这就是我最终得到的结果:

SELECT
posts.id AS post_id,
posts.title AS post_title,
CASE
WHEN EXISTS (
  SELECT *
  FROM likes
  WHERE posts.id = likes.post_id
  AND likes.user_id = 1
) THEN TRUE
  ELSE FALSE END
  AS liked
FROM posts;

尽管我能够解决它,但也感谢@wildplasser的回答。


阅读 147

收藏
2021-05-16

共1个答案

小编典典

数据(我需要稍作更改,因为不应将其分配给序列号):


 CREATE TABLE posts (
  id serial,
  title varchar
);

CREATE TABLE users (
  id serial,
  name varchar
);

CREATE TABLE likes (
  id serial,
  user_id int,
  post_id int
);

INSERT INTO posts (title) VALUES ('First Post');
INSERT INTO posts (title) VALUES ('Second Post');
INSERT INTO posts (title) VALUES ('Third Post');

INSERT INTO users (name) VALUES ('Obama');
INSERT INTO users (name) VALUES ('Trump');

INSERT INTO likes (user_id, post_id) VALUES (1, 1);
INSERT INTO likes (user_id, post_id) VALUES (2, 1);
INSERT INTO likes (user_id, post_id) VALUES (2, 2);

-- I want to retrieve a list of ALL of the posts and whether or not a specific user has liked that post
SELECT id, title
        , EXISTS(
                --EXISTS() yields a boolean value
                SELECT *
                FROM likes lk
                JOIN users u ON u.id = lk.user_id AND lk.post_id=p.id
                WHERE u.name ='Obama'
                ) AS liked_by_Obama
FROM posts p
        ;

结果:


 id |    title    | liked_by_obama 
----+-------------+----------------
  1 | First Post  | t
  2 | Second Post | f
  3 | Third Post  | f
(3 rows)
2021-05-16