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 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路