MySQL:为我与之交谈的每个用户从表中选择最新记录

时间:2015-03-08 15:16:49

标签: mysql

我有2张桌子。

users架构:

enter image description here

private_messages架构:

enter image description here

time_sent是日期时间。所有其他字段都是varchars和ints。

sender_idreceiver_id都引用id中的users

我想要的是什么:

给定users id,比如说1,为每个其他用户选择最后发送的消息(给定用户是发送消息还是其他用户发送消息)。它应该返回private_messages表的所有列以及其他用户的username,并按time_sent排序。

我试图实现的功能是当您打开所有短信时,您可以看到您和其他人之间发送的最后一条消息的预览。由于给定用户ID可以显示在sender_idreceiver_id中,因此此查询会导致我失败。请帮我写出查询。

这是导出的sql代码,用于创建表及其内容(以防万一你需要测试一下):

users

private_messages

private_messages 2

2 个答案:

答案 0 :(得分:1)

您可以采用以下技术获取每组最大值

select 
u1.username as sender, 
u2.username as receiver, 
m.message,
m.time_sent 
from private_messages m 
inner join users u1 on u1.id = m.sender_id 
inner join users u2 on u2.id = m.receiver_id 
left join private_messages m1 on m1.sender_id = m.sender_id 
and m1.receiver_id = m.receiver_id 
and m1.time_sent > m.time_sent 
where m.sender_id = 1 
and m1.id is null ; 

您也可以使用

and m1.id > m.id 

而不是

and m1.time_sent > m.time_sent 

如果id表中的private_messages自动递增

如果您需要将数据视为给定用户的发送方和接收方,则条件为

 where ( m.sender_id = 1 or m.receiver_id = 1 ) and m1.id is null

而不是

where m.sender_id = 1 
and m1.id is null ;

http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html

答案 1 :(得分:1)

这应该可以解决问题

      SELECT U.username,
             U2.username,
             IF(PM.sender_id = U.id, 'Sent', 'Received') AS `action`,
             PM.message, 
             PM.time_sent             
        FROM users U
  INNER JOIN private_messages PM ON (PM.sender_id = U.id OR PM.receiver_id = U.id)
  INNER JOIN users U2 ON (U2.id = IF(PM.sender_id = U.id, PM.receiver_id, PM.sender_id))  
       WHERE NOT EXISTS (
                SELECT *
                  FROM private_messages NXT_PM
                 WHERE NXT_PM.time_sent > PM.time_sent
                   AND (
                         ( NXT_PM.sender_id = PM.sender_id  AND NXT_PM.receiver_id = PM.receiver_id )
                       OR 
                         (  NXT_PM.receiver_id = PM.sender_id  AND NXT_PM.sender_id = PM.receiver_id )
                       )
             )       
         AND U.username = 'Kacy'
    ORDER BY time_sent DESC

返回:

+----------+----------+----------+----------+---------------------+
| username | username | action   | message  | time_sent           |
+----------+----------+----------+----------+---------------------+
| Kacy     | liz      | Sent     | hi again | 2015-03-08 10:47:26 |
| Kacy     | Jamie    | Sent     | hi       | 2015-03-07 23:01:18 |
| Kacy     | tracy    | Received | hi       | 2015-03-06 12:04:34 |
+----------+----------+----------+----------+---------------------+
3 rows in set (0.02 sec)