PostgreSQL
 sql >> Teknologi Basis Data >  >> RDS >> PostgreSQL

Hubungan banyak-ke-banyak untuk menentukan apakah pengguna menyukai kiriman

Data (Saya perlu mengubahnya sedikit, karena seseorang tidak boleh menetapkan ke serial):

 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
        ;

Hasil:

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


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara Mendapatkan Baris Terakhir Per Grup di PostgreSQL

  2. Bagaimana cara bekerja dengan tabel tanpa PRIMARY KEY di Hibernate?

  3. Upser dinamis di postgresql

  4. Docker - Postgres dan pgAdmin 4:Koneksi ditolak

  5. Bagaimana pg_sleep_for() Bekerja di PostgreSQL