dsij89625 2016-07-16 11:25
浏览 28
已采纳

由MySQL中的发送方接收方或接收方发送方分组

I am trying to make an inbox section of messages. My problem goes like this.

id   userfrom   userto

1                     a                b

2                     b                a
now i have to select only one message of conversation between a and b.I have also tried some mysql queries like this one

$query="select * 
        from messages 
        where userfrom='a' || userto='a' 
        group by userto 
        order by id desc"

but it shows both messages of conversation but i only want to show only one message of the conversation

  • 写回答

1条回答 默认 最新

  • douwo1517 2016-07-16 11:38
    关注

    You can try the following conditional group by query:

    select * 
    from messeages 
    where userfrom='a' OR userto='a' 
    group by IF(userfrom > userto, userfrom,userto),
             IF(userfrom > userto, userto,userfrom)
    order by id desc
    

    <kbd>WORKING DEMO</kbd>

    Note: Actually in the GROUP BY clause the group by is done based on the following logic:

    GROUP BY greater value of (userfrom,userto), lower value of(userfrom,userto)

    Example:

    userfrom ='a' and userto='b' 
    
    userfrom ='b' and userto='a'
    

    In the above two rows greater value is 'b' and lower value is 'a.Thus from both rows GROUP BY will be applied first on b then on a.

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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题