PostgreSQL
 sql >> Base de données >  >> RDS >> PostgreSQL

Relation plusieurs-à-plusieurs pour déterminer si l'utilisateur a aimé une publication

Données (j'avais besoin de les modifier un peu, car il ne faut pas les attribuer aux publications en série) :

 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
        ;

Résultats :

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