Mysql 基于外部行集查找行
我有3张用于聊天系统的桌子:Mysql 基于外部行集查找行,mysql,Mysql,我有3张用于聊天系统的桌子: 对话此表包含id和时间戳 对话\u参与者告诉我哪些用户正在聊天 对话消息此聊天中发送的消息(还保留发件人id) 这个设置对我来说非常好,但现在我想做一个“反向”查找。我知道哪些用户将开始新的聊天,我想知道这个特定的组是否已经在数据库中进行了对话。有没有一种方法可以基于一组动态的外部行来查找行 (最好不要使用类似枢轴的技巧) 或者我的数据库设计有缺陷,我应该改变吗 CONVERSATION id int auto_increment start timesta
CONVERSATION
id int auto_increment
start timestamp
CONVERSATION_PARTICIPANT
conversation_id int (foreign key to conversation)
participant_id int (foreign key to users table)
CONVERSATION_MESSAGE
id int auto_increment
conversation_id int (foreign key to conversation)
author_id int
time timestamp
message text
这假设您:
- 有一个以逗号分隔的参与者id的->$列表
- 了解参与者人数->数量
- 使用WHERE子句中的一个参与者->$participant
仅供参考:WHERE子句的目的是限制潜在对话的数量。如果您有一组用户要聊天,您想查找其中至少有两个用户参与的对话还是所有用户都参与的对话?如果有4个人和3个人正在尝试聊天,那么即使有1个人不在,也应该选择该对话吗?它应该是最近的对话吗?它应该只匹配完全相同的用户集。因此,3个之前聊过4次的人应该开始新的对话。这是最近的一次对话,与此无关,因为每一组用户应该只有一次对话。这太棒了!您甚至考虑到列表中可能会有更多用户。谢谢
SELECT conversation_participant.conversation_id AS conversation_id
, SUM(IF(members.participant_id IN ($list),1,0)) AS member_count
, COUNT(*) AS total
FROM conversation_participant
JOIN conversation_participant AS members
ON members.conversation_id = conversation_participant.conversation_id
WHERE conversation_participant.participant_id = $participant
GROUP BY conversation_id
HAVING member_count = total
AND member_count = $qty;