sql >> Base de Datos >  >> RDS >> PostgreSQL

Relación de muchos a muchos para determinar si al usuario le ha gustado una publicación

Datos (necesitaba cambiarlo un poco, porque no se debe asignar a seriales):

 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
        ;

Resultados:

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