MySQL数据库架构,用于简单聊天一对一

时间:2017-12-15 04:51:49

标签: php mysql chat mariadb

我尝试与这些架构进行简单的聊天:

mes_id  int(10) unsigned Auto Increment  
mes_useid_receiver  int(10) unsigned     
mes_useid_sender    int(10) unsigned     
mes_date    int(10) unsigned     
mes_message text     
mes_read    tinyint(3) unsigned [0]  
mes_visible_for_who int(10) unsigned NULL   NULL = both; 0 = none; ID user

问题是,如何获取收到的消息和发送消息的联系人列表?

我正在尝试这样的事情:

SELECT use_name, MAX(mes_date) AS date 
FROM message JOIN user ON mes_useid_receiver=use_id 
WHERE uti_id!=1 
AND (mes_useid_receiver=1 OR mes_useid_sender=1) 
AND (mes_visible_for_who IS NULL OR mes_visible_for_who=1) 
GROUP BY use_id 
ORDER BY date DESC

但是通过此查询,我可以获得向 user_id = 1 发送消息的联系人,我还希望获得 user_id = 1 发送的联系人消息。

编辑:

通过联盟我几乎可以得到我想要的东西:

SELECT use_id, use_name, mes_read FROM message
JOIN user ON mes_useid_receiver=use_id
WHERE use_id!=1 
AND (mes_useid_receiver=1 OR mes_useid_sender=1) 
AND (mes_visible_for_who IS NULL OR mes_visible_for_who=1) GROUP BY use_id

UNION

SELECT use_id, use_name, mes_read FROM message
JOIN user ON mes_useid_sender=use_id
WHERE use_id!=1 
AND (mes_useid_receiver=1 OR mes_useid_sender=1) 
AND (mes_visible_for_who IS NULL OR mes_visible_for_who=1) GROUP BY use_id

我需要mes_date来排序列表,但是如果我选择了mes_date,我将获得重复的行。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

如果你要进入这个根,那么我的建议就像下面这样:

def subscribed

还要看看你是否可以避免在每个选择中进行分组(你会感觉性能不佳)

问候