sql >> Database teknologi >  >> RDS >> PostgreSQL

Mange-til-mange forhold for at afgøre, om brugeren har kunnet lide et opslag

Data (jeg havde brug for at ændre det lidt, fordi man ikke skulle tildele til serier):

 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
        ;
 

Resultater:

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

  1. Konvertering af en IP til en Long i MySQL

  2. Sender FieldName som parameter i MySQL Stored Procedure

  3. COALESCE() for tomme (men ikke null) felter

  4. Kan ikke oprette indledende forbindelser af puljeproblemer i Grails