微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php-按2列分组,与顺序无关

以下查询

select a.message, a.sender_id, a.rec_id, a.id, a.is_seen, b.total_msg, b.last_id, users.name
from tbl_message a left join users on (users.id=a.sender_id)
inner join
  (select sender_id, rec_id, max(id) last_id, count(*) total_msg
         from tbl_message group by sender_id,rec_id
  )b on a.id=b.last_id 
order by a.id desc 

给出如下结果:

+----------------------------+-----------+--------+----+---------+-----------+---------+------+
| message                    | sender_id | rec_id | id | is_seen | total_msq | last_id | name |
+----------------------------+-----------+--------+----+---------+-----------+---------+------+
| latest testing l5 aug      |         2 |     1  | 12 |      0  |       5   |     12  | B    |
| testing                    |         1 |     2  | 11 |      1  |       3   |     11  | A    |
| this msg of A              |         1 |     3  |  9 |      0  |       1   |      9  | A    |
| this is again 3rd msg of C |         3 |     1  |  6 |      1  |       3   |      6  | C    |
+----------------------------+-----------+--------+----+---------+-----------+---------+------+

我想要的结果是:

对于sender_id / rec_id = 1或2 id = 12,对于sender_id / rec_id = 1或3 id = 9

解决方法:

看起来您需要与所有分组的列一起加入

尝试这个

 SELECT a.message
    ,a.sender_id
    ,a.rec_id
    ,a.id
    ,a.is_seen
    ,b.total_msg
    ,b.last_id
    ,users.NAME
FROM tbl_message a
LEFT JOIN users ON (users.id = a.sender_id)
INNER JOIN (
    SELECT sender_id
        ,rec_id
        ,max(id) last_id
        ,count(*) total_msg
    FROM tbl_message
    GROUP BY sender_id
        ,rec_id
    ) b ON a.sender_id=b.sender_id and a.rec_id=b.rec_id and a.id = b.last_id
ORDER BY a.id DESC

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐