dtqpw68806 2017-12-15 04:51
浏览 73
已采纳

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

I trying to do a simple chat with these schema:

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

The problem is, how I can get the list of contacts of received messages and sent messages?

I'm trying something like this:

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

But with this query I just can get the contacts that send a message to user_id = 1, I want to get also the contacts that user_id = 1 sent messages.

Edited:

With union I can get almost that I want:

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

I need the mes_date to order the list, but if I select the mes_date I will get duplicate rows.

Thanks for the help.

  • 写回答

1条回答 默认 最新

  • doubi4531 2017-12-15 05:36
    关注

    if you are going in this root then my suggetion is something like below:

    SELECT *  FROM(
    
        (SELECT use_id, use_name, mes_read ,mes_date 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 ,mes_date 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 
    
    ) as d Order By mes_date desc
    

    also see if you can avoid grouping in within each selection ( you will feel a bad performance )

    regards

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP