mysql查询以获取用户的消息(发送或接收)

时间:2018-01-10 11:42:31

标签: mysql sql

我需要从两个表user_table和message_log表中获取记录,其中包含发送或接收的指定user_id最近消息以及发送者或接收者用户详细信息。

USER_TABLE:

USER_ID | USER_NAME | user_profile_pic

message_log:

MSG_ID | msg_from_user | msg_to_user | msg_message | msg_datetime

结果应该是:

USER_ID | USER_NAME | user_profile_pic | MSG_ID | msg_from | msg_to | msg_message | msg_datetime

233 | ravi | /img/img1.png | 90 | 234 | 233 |嗨我的消息| 2018-01-08 02:02:14

235 | ravi | /img/img1.png | 90 | 235 | 234 |嗨那里| 2018-01-05 12:02:28

230 | ravi | /img/img1.png | 90 | 230 | 234 |再见| 2018-01-05 12:02:28

我试过如下:

SELECT tbl_user.user_id,tbl_user.user_name,tbl_user.user_profile_pic, tbl_message_log_temp.* 
FROM tbl_user

LEFT JOIN ( 
    SELECT s1.* FROM tbl_message_log as s1 LEFT JOIN tbl_message_log AS s2 ON s1.msg_from_user_id = s2.msg_from_user_id AND s1.msg_datetime < s2.msg_datetime WHERE s2.msg_from_user_id IS NULL

    ) as tbl_message_log_temp ON (tbl_user.user_id = tbl_message_log_temp.msg_from_user_id) 
WHERE `user_id` IN (

     SELECT DISTINCT(`msg_to_user_id`) from tbl_message_log WHERE `msg_from_user_id` = 234 ORDER BY `msg_id` DESC)

但我没有收到最近的消息。

0 个答案:

没有答案