无论顺序如何,都按2列分组

时间:2015-08-15 13:25:35

标签: php mysql sql

以下查询

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 or 2 id = 12sender_id/rec_id = 1 or 3 id = 9

2 个答案:

答案 0 :(得分:1)

您似乎需要加入所有已分组的列

试试这个

 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

答案 1 :(得分:1)

听起来您希望按sender_id,rec_id参与者对对行进行分组,无论它们出现在哪个顺序(即sender_id,rec_idrec_id,sender_id应属于同一组)。< / p>

如果是,请从

更改group by
group by sender_id, rec_id

group by least(sender_id,rec_id), greatest(sender_id,rec_id)

使用greatestleast将确保参与者将每个会话分组,无论他们出现在哪个顺序。

相关问题