Skip to content

Instantly share code, notes, and snippets.

@abatilo
Created September 7, 2021 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abatilo/b6d2de279b1d33100095ac9211dabf67 to your computer and use it in GitHub Desktop.
Save abatilo/b6d2de279b1d33100095ac9211dabf67 to your computer and use it in GitHub Desktop.
DROP TABLE IF EXISTS sent;
DROP TABLE IF EXISTS message;
DROP TABLE IF EXISTS recipient;
CREATE TABLE IF NOT EXISTS recipient (
id serial primary key
);
CREATE TABLE IF NOT EXISTS message (
id serial primary key
);
CREATE TABLE IF NOT EXISTS sent (
id serial primary key,
recipient_id bigint NOT NULL REFERENCES recipient(id) ON UPDATE CASCADE,
message_id bigint NOT NULL REFERENCES message(id) ON UPDATE CASCADE
);
INSERT INTO recipient VALUES (1), (2), (3);
INSERT INTO message VALUES (1), (2), (3), (4), (5);
INSERT INTO sent(recipient_id, message_id) VALUES (1, 1), (1, 2), (1, 3), (1, 4);
WITH unsent AS (
SELECT id FROM message
EXCEPT
SELECT message_id FROM sent WHERE sent.recipient_id = 1
)
SELECT id FROM unsent ORDER BY RANDOM() LIMIT 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment