douyang5943 2015-04-11 14:51
浏览 17
已采纳

按更多组合分组

I have the following table to represent a conversation between users.

message | user1 | user2 | unixtime
msg1    | 14    | 21    | -
msg2    | 21    | 12    | -
msg1    | 14    | 18    | -
msg3    | 14    | 21    | -
msg2    | 18    | 14    | -
msg4    | 21    | 12    | -

I want to show a list of a a specific user's conversations by selecting all messages with current_user = user1 or user2. So far this SELECT will select the correct messages but the grouping doesn't work correctly.

SELECT * FROM (
    SELECT * FROM messages
    WHERE user1 = '".$_SESSION['login']['ID']."'
    OR user2 = '".$_SESSION['login']['ID']."'
    ORDER BY unixtime DESC
) as list
GROUP BY user1, user2
ORDER BY unixtime DESC

It will only group the messages with the same user1 and user2 and not if the two users are reversed. Is this done by a more advanced grouping or should I join the table in some way?

  • 写回答

1条回答 默认 最新

  • doume5227 2015-04-11 15:00
    关注

    It is unclear what you want the query to do, because you are using group by and select *. The select * returns indeterminate values from matching rows. I don't know why anyone would want to do this. You can read about this in the documentation.

    If you want to counts the messages:

    SELECT least(user1, user2), greatest(user1, user2), count(*)
    FROM messages
    WHERE '".$_SESSION['login']['ID']."' in (user1, user2)
    GROUP BY least(user1, user2), greatest(user1, user2)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退