MySQL选择mulitple Row / Group Multiple / Order

时间:2016-02-20 17:15:33

标签: php mysql chat

我正在建立一个聊天系统,其中用户A可以与用户B讨论主题X或Y.

我的表如下:

Message ID | message | sender | receiver | topic
1            Helo      1        2           X
2            Lorem     2        1           X
3            Foo       1        2           Y
4            Bar       2        1           X
5            Test      2        1           Y
6            Hello2    1        3           X

所以我想获得每个用户和主题的第6个用户1对话列表。目前我得到了

SELECT messageid, sender,topic, receiver AS friend FROM table WHERE sender = 1 || receiver = 1 GROUP BY topic,friend ORDER BY id DESC LIMIT 0,6

但是这并没有选择最后消息。因为之后我创建了一个列表,并且不会显示最后的对话...

在本例中,我需要一个如下列表:

 Message ID | sender | topic| friend
 6            1         X      3
 5            2         Y      1
 4            2         X      1

以下选择它有效! select * from (select Message_ID,sender,topic, receiver AS friend from tab where sender = 1 || receiver = 1 order by Message_ID desc) temp group by topic order by Message_ID desc

作品!

2 个答案:

答案 0 :(得分:1)

如果您想要给定用户的最后一条消息 id 的ID:

select (case when sender = 1 then receiver else sender end) as other,
       topic, max(messageid)
from messages
where sender = 1 or receiver = 1
group by (case when sender = 1 then receiver else sender end) ;

然后您可以使用它来获取所有信息:

select m.*
from messages m join
     (select (case when sender = 1 then receiver else sender end) as other,
             topic, max(messageid) as messageid
      from messages
      where sender = 1 or receiver = 1
      group by (case when sender = 1 then receiver else sender end) 
     ) mm
     on mm.messageid = m.messageid;

答案 1 :(得分:-1)

我猜,问题是在group by子句中选择了第一行。 在分组之前使用order by子句可以很容易地解决它。

select * from
(select Message_ID,sender,topic, receiver AS friend from tab
 where sender = 1 || receiver = 1 
order by Message_ID desc) temp
group by friend order by Message_ID desc

请在http://sqlfiddle.com/#!9/bf53d/10

验证答案