我有两个表,如用户,消息
Users Table
id,uname,email,profile_pic.....
messages Table
id,from_id,to_id,message,created_at
这里from_id和to_id是用户表id的外键。
我希望获得最新消息用户的消息。我试过这样的
SELECT
`u`.`firstname`,
`u`.`lastname`,
`u`.`profile_photo`,
`u`.`id`,
`u2`.`firstname`,
`u2`.`lastname`,
`u2`.`profile_photo`,
`u2`.`id`,
`message`,
`messages`.`created_at`,
`messages`.`from_id`,
`messages`.`to_id`,
`messages`.`id` AS `mid`
FROM
`messages`
INNER JOIN
`users` AS `u` ON `u`.`id` = `messages`.`from_id`
INNER JOIN
`users` AS `u2` ON `u2`.`id` = `messages`.`to_id`
WHERE
(from_id = 26 OR to_id = 26)
GROUP BY
`u`.`id`,
`u2`.`id`
ORDER BY
`messages`.`id` DESC
但我只收到第一条消息。但是我需要通过messages.id降序获取 - order
示例数据
User table
id | firstname | email | mobile
---------------------------------------------
1 | ram | ram@gmail.com | 9876543210
----------------------------------------------
2 | jack | jack@gmail.com | 8876543216
----------------------------------------------
3 | rams | rams@gmail.com | 7876543215
----------------------------------------------
4 | devid | devid@gmail.com | 9876543220
----------------------------------------------
5 | sri | sri@gmail.com | 8876543212
----------------------------------------------
消息表
id | from_id | to_id | message | created_at
-------------------------------------------------------
1 | 1 | 2 | how r u | 2017-02-03
-------------------------------------------------------
2 | 2 | 1 | fine | 2017-02-03
-------------------------------------------------------
3 | 2 | 3 | hi | 2017-02-03
-------------------------------------------------------
4 | 3 | 2 | hello | 2017-02-03
-------------------------------------------------------
5 | 1 | 2 | hello how are you | 2017-02-03
-------------------------------------------------------
6 | 3 | 1 | good night | 2017-02-03
-------------------------------------------------------
8 | 1 | 3 | good night rams | 2017-02-03
-------------------------------------------------------
7 | 3 | 1 | hello ram | 2017-02-03
-------------------------------------------------------
预期产出:
firstname | message | mid | uid
-----------------------------------------
rams | hello ram | 7 | 3
-----------------------------------------
jack | hello how are you | 5 | 2
-----------------------------------------
这是我们假设登录用户是来自用户表
的ram(id = 1)的聊天应用程序