Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. User
  2. id
  3. ...
  4.  
  5. Conversation
  6. id
  7. user_id1
  8. user_id2
  9. cnt_new_msg
  10. last_msg_id
  11.  
  12. Message
  13. id
  14. conversation_id
  15. sender_id
  16. type
  17. is_read
  18. created_at
  19.  
  20. SELECT *
  21. FROM conversation c
  22. LEFT JOIN message m ON m.id = c.last_msg_id l.last_ms
  23. WHERE user_id1=[current_user_id] OR user_id2=[current_user_id]
  24.  
  25. CREATE TABLE users (user_id serial PRIMARY KEY, ...)
  26.  
  27. CREATE TABLE conversation (
  28. conversation_ id serial PRIMARY KEY
  29. , user_id1 int NOT NULL REFERENCES users
  30. , user_id2 int NOT NULL REFERENCES users
  31. -- cnt_new_msg -- redundant
  32. -- last_msg_id
  33. , created_at timestamptz NOT NULL DEFAULT now()
  34. );
  35.  
  36. CREATE TABLE message (
  37. message_id serial PRIMARY KEY
  38. conversation_id int NOT NULL REFERENCES conversation
  39. sender "char" NOT NULL CHECK (sender IN ('1', '2')
  40. message text NOT NULL
  41. type ???
  42. unread boolean NOT NULL DEFAULT TRUE
  43. created_at timestamptz NOT NULL DEFAULT now()
  44. );
  45.  
  46. CREATE VIEW conversation_plus_ct AS
  47. SELECT c.*
  48. , count(m.unread OR NULL) AS cnt_new_msg
  49. , max(m.created_at) AS last_msg_id
  50. FROM conversation c
  51. JOIN message m USING (conversation_id);
  52.  
  53. SELECT *
  54. , count(m.unread OR NULL) AS cnt_new_msg
  55. , max(m.created_at) AS last_msg_id
  56. FROM conversation c
  57. LEFT JOIN message m USING (conversation_id)
  58. WHERE [current_user_id] IN (user_id1, user_id2);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement