Order By Not Working in double select查询

时间:2018-02-05 15:49:25

标签: mysql

我正在尝试显示每个用户的最新消息;它应该对具有相同用户ID的多条消息进行分组,该用户ID来自另一个ID fromUserId

这是从同一用户返回多条消息的查询;它应该通过 ID 按降序对消息进行排序,但查询不排序。它应该以降序显示它们,即3,2,1 ......

SELECT DATA.* FROM (
SELECT a.*, b.firstName, b.middleName, b.lastName FROM `users_messages` a LEFT JOIN `users` b ON b.id = a.fromUserId 
WHERE a.toUserId = '2' ORDER BY a.id DESC) DATA 

Here is a screenshot of the first result

所以我尝试从用户ID fromUserID 对它们进行分组,结果为1和3,它应该返回2和3,因为2是用户ID 3的最新消息

SELECT DATA.* FROM (
SELECT a.*, b.firstName, b.middleName, b.lastName FROM `users_messages` a LEFT JOIN `users` b ON b.id = a.fromUserId 
WHERE a.toUserId = '2' ORDER BY a.id DESC) DATA GROUP BY DATA.fromUserId 

Here is a screenshot of the second result

1 个答案:

答案 0 :(得分:0)

使用子查询从userid / touserid

获取最新消息
SELECT id,touserid,fromuserid,message,date
FROM users_messages um
where id = (select max(um1.id) from users_messages um1 where um1.touserid = um.touserid and um1.fromuserid = um.fromuserid) 
order by id desc

+------+----------+------------+--------------------------------------+---------------------+
| id   | touserid | fromuserid | message                              | date                |
+------+----------+------------+--------------------------------------+---------------------+
|    3 |        2 |          4 | Hello Hello Hello Hello Hello Hello  | 2018-02-05 21:37:29 |
|    2 |        2 |          3 | Test 2                               | 2018-02-05 21:37:25 |
+------+----------+------------+--------------------------------------+---------------------+
2 rows in set (0.00 sec)