SQL查询以搜索用户之间的最后一次对话

时间:2014-09-14 13:25:57

标签: php mysql

我有以下消息交换结构数据库

DB - User
id_user - name - last_name
1          A       A
2          B       B
3          C       C
4          D       D
5          E       E 

DB Message -conversations保存在以下结构中

id - from - to -  message - date
1     1     2    msg(here)  (date here)
2     2     1      
3     1     2 
4     4     1
5     4     1
6     1     5

我需要的帮助是创建一个SQL查询,以便在发送或接收时返回最后一个idependete对话 exmeplo您获得对话用户1所需的结果

id - from - to ...
 3     1      2   
 5     4      1
 6     1      5

即如果没有重复专业人员订购其他人并获取用户表中的名称和姓氏以显示在屏幕上,则寻求发送或接收的独立最后消息

屏幕上的最终结果

 mensagens
 name last_name  mensagem
  b      b        mensagem
  d      d        mensagem
  e      e        mensagem



SELECT distinct * FROM menssage inner join user on from = id_user where to LIKE '$session' 
union SELECT distinct * FROM message inner join user on to = id_user where from LIKE '$session' 
group by id_user  order by  id asc

1 个答案:

答案 0 :(得分:0)

逻辑很简单:您创建一个数据集作为UserID(同时包含& to),date&信息。这样你就可以得到所有已发送的数据。在单个数据集中接收消息。 - 现在生活很简单,只需按日期时间排序即可。为该用户选择了最新的1条消息&用它的名字来表示它,Lname&消息:)

PostgreSQL的示例代码。

    create table DBuser (userid int, name char(10), last_name char(20));
    insert into DBuser values(1, 'A', 'LA');
    insert into DBuser values(2, 'B', 'LB');
    insert into DBuser values(3, 'C', 'LC');
    insert into DBuser values(4, 'D', 'LD');
    insert into DBuser values(5, 'E', 'LE');
    select * from DBUser


    create table DBMessages (id int, Ufrom int, Uto int, message text, Mdate time);
    insert into DBMessages values (1, 1, 2, 'Hello 1', CURRENT_time);
    insert into DBMessages values (2, 2, 1, 'Hello 2', CURRENT_time);
    insert into DBMessages values (3, 1, 2, 'Hello 3', CURRENT_time);
    insert into DBMessages values (4, 4, 1, 'Hello 4', CURRENT_time);
    insert into DBMessages values (5, 4, 1, 'Hello 5', CURRENT_time);
    insert into DBMessages values (6, 1, 5, 'Hello 6', CURRENT_time);

    select * from DBMessages;

    select name, 
           last_name, 
           message 
      from DBuser, 
    (select userID, 
            message, 
            rank() over (PARTITION BY userID order by Mdate desc) as rank 
       from (select Ufrom as userID, 
                    message,
                    Mdate
               from DBMessages
               union all
             select Uto as userID, 
                    message,
                    Mdate
               from DBMessages
           )  as data 
    ) as rankeddata 
   where rank =1 
   and rankeddata.userID = DBUser.userid;

Name    Last_Name   Message
"A"     "LA"        "Hello 6"
"B"     "LB"        "Hello 3"
"D"     "LD"        "Hello 5"
"E"     "LE"        "Hello 6"