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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...