我有一个对话表,一个会话表和一个播放器表。我想为玩家的任何一组(意思是不同的组,不考虑排序)找到一个且只有一个conversation_owned。
converation_owned列conversation_id和player_id是外键
CREATE TABLE conversation
(
id INTEGER PRIMARY KEY NOT NULL,
created_at TIMESTAMP WITH TIME ZONE,
modified_at TIMESTAMP WITH TIME ZONE,
count INTEGER
);
CREATE UNIQUE INDEX conversation_id_uindex ON conversation (id);
CREATE TABLE conversation_owned
(
id INTEGER PRIMARY KEY NOT NULL,
conversation_id BIGINT DEFAULT nextval('conversation_owned_conversation_id_seq'::regclass) NOT NULL,
player_id INTEGER,
created_at TIMESTAMP WITH TIME ZONE,
modified_at TIMESTAMP WITH TIME ZONE,
CONSTRAINT conversation_owned_conversation_id_fk FOREIGN KEY (conversation_id) REFERENCES conversation (id),
CONSTRAINT conversation_owned_player_id_fk FOREIGN KEY (player_id) REFERENCES
);
CREATE UNIQUE INDEX conversation_owned_id_uindex ON conversation_owned (id);
CREATE TABLE player
(
id INTEGER PRIMARY KEY NOT NULL,
player_name TEXT NOT NULL
);
例如:如果我在iMessage或Facebook Messenger撰写窗口中键入多个联系人(Billy,Joe和Sue),该应用程序将检索我与我自己,Billy,Joe或Sue的任何现有对话,无论我的顺序如何进入他们。但如果我进入比利和乔(而不是苏),我可能会有一个不同的对话。我正在寻找能够以相对有效的方式给我这种行为的查询。
请注意,如果我将“count”列添加到会话表中,该会话表中包含会话中的参与者数量,使其如下所示:
CREATE TABLE conversation
(
id INTEGER PRIMARY KEY NOT NULL
);
我可以使用此查询来获取我想要的内容,但在我看来,我应该能够在不添加和维护会话中的“计数”列的情况下执行此操作!
SELECT
*
FROM
conversation_owned
INNER JOIN conversation ON conversation_owned.conversation_id=conversation.id
WHERE
conversation_id
NOT IN (
SELECT
conversation_owned.conversation_id
FROM
conversation_owned
WHERE
conversation_owned.player_id
NOT IN (${playerIDs})
)
AND
conversation.count = ${participantCount}
AND
conversation_owned.player_id = ${requestingPlayerID};