在我的应用中,用户
CREATE TABLE users (
id bigserial PRIMARY KEY,
username varchar(50) NOT NULL
);
可以发送消息
CREATE TABLE messages (
id bigserial PRIMARY KEY,
from_id bigint NOT NULL REFERENCES users ON DELETE RESTRICT,
body text NOT NULL CHECK (body <> ''),
created_at timestamp(0) NOT NULL DEFAULT LOCALTIMESTAMP(0),
is_read boolean NOT NULL DEFAULT TRUE
);
对许多收件人
CREATE TABLE message_recipients (
message_id bigint NOT NULL REFERENCES messages ON DELETE CASCADE,
user_id bigint NOT NULL REFERENCES users ON DELETE RESTRICT,
is_read boolean NOT NULL DEFAULT FALSE,
PRIMARY KEY (message_id, user_id)
);
如何选择多个用户之间发送的邮件,以便is_read
列指定其中一个用户是否已阅读邮件?我还想包含一个名为to_ids
的列,其中包含以逗号分隔的邮件收件人用户ID列表。
,例如,如何获取用户1,2和3之间发送的消息,以便is_read
列指定用户1是否已阅读消息? to_ids
列包含来自集{1, 2, 3}
的两个以逗号分隔的ID。
结果集应包含以下列:id, from_id, to_ids, body, created_at, is_read
。
样本数据
SELECT * FROM users;
# id | username |
# ----+------------+
# 1 | user1 |
# 2 | user2 |
# 3 | user3 |
SELECT * FROM messages;
# id | from_id | body | created_at | is_read
# ----+---------+---------------------+---------------------+---------
# 1 | 1 | This is message 1. | 2016-12-16 11:41:50 | t
# 2 | 2 | This is message 2. | 2016-12-16 11:41:50 | t
# 3 | 3 | This is message 3. | 2016-12-16 11:41:50 | t
# 4 | 1 | This is message 4. | 2016-12-16 11:41:50 | t
# 5 | 2 | This is message 5. | 2016-12-16 11:41:50 | t
# 6 | 3 | This is message 6. | 2016-12-16 11:41:50 | t
# 7 | 1 | This is message 7. | 2016-12-16 11:41:50 | t
SELECT * FROM message_recipients;
# message_id | user_id | is_read
# ------------+---------+---------
# 1 | 2 | f
# 1 | 3 | f
# 2 | 1 | f
# 2 | 3 | f
# 3 | 1 | f
# 3 | 2 | f
# 4 | 2 | f
# 4 | 3 | f
# 5 | 1 | f
# 5 | 3 | f
# 6 | 1 | f
# 6 | 2 | f
# 7 | 2 | f
# 7 | 3 | f
预期产出
# id | from_id | to_ids | body | created_at | is_read
# ----+---------+--------+---------------------+---------------------+---------
# 1 | 1 | 2,3 | This is message 1. | 2016-12-16 11:41:50 | t
# 2 | 2 | 1,3 | This is message 2. | 2016-12-16 11:41:50 | f
# 3 | 3 | 1,2 | This is message 3. | 2016-12-16 11:41:50 | f
# 4 | 1 | 2,3 | This is message 4. | 2016-12-16 11:41:50 | t
# 5 | 2 | 1,3 | This is message 5. | 2016-12-16 11:41:50 | f
# 6 | 3 | 1,2 | This is message 6. | 2016-12-16 11:41:50 | f
# 7 | 1 | 2,3 | This is message 7. | 2016-12-16 11:41:50 | t