Guest User

Untitled

a guest
Oct 19th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.70 KB | None | 0 0
  1. BEGIN;
  2.  
  3. CREATE TABLE users (
  4. id SERIAL PRIMARY KEY NOT NULL,
  5. name VARCHAR(255) NOT NULL
  6. );
  7.  
  8. CREATE TABLE connections (
  9. id SERIAL PRIMARY KEY NOT NULL,
  10. user_id_1 INTEGER NOT NULL,
  11. user_id_2 INTEGER NOT NULL
  12. );
  13.  
  14. INSERT INTO users (name) VALUES ('a'), ('b'), ('c');
  15.  
  16. INSERT INTO connections (user_id_1, user_id_2) VALUES
  17. (1, 2),
  18. (2, 3),
  19. (3, 1);
  20.  
  21. SELECT
  22. friends.id
  23. FROM
  24. users
  25. JOIN connections ON users.id = connections.user_id_1
  26. JOIN users AS friends ON connections.user_id_2 = friends.id
  27. WHERE
  28. users.id = 1
  29. UNION
  30. SELECT
  31. friends.id
  32. FROM
  33. users AS friends
  34. JOIN connections ON friends.id = connections.user_id_1
  35. JOIN users ON connections.user_id_2 = users.id
  36. WHERE
  37. users.id = 1;
  38.  
  39. ROLLBACK;
Add Comment
Please, Sign In to add comment