MySQL在其他列中显示每个不同值的最新日期行?

时间:2012-08-18 03:15:04

标签: mysql sql greatest-n-per-group

我正在使用一个mysql查询,该查询应该选择用户发送或发送的所有消息。我需要使用相同的UID对所有消息进行分组,以便为​​每个不同用户显示一个单独的线程(这意味着它应该消除除具有相同UID的最后一个消息之外的所有消息)。我的问题是我开始使用GROUP BY来执行此操作,但有时保留的行实际上是旧消息而不是最新消息。

这就是我的尝试:

SELECT `UID`, `Name`, `Text`, `A`.`Date`
FROM `Users`
INNER JOIN (
    (
    SELECT *, To_UID AS UID FROM `Messages` WHERE `From_UID` = '$userID' AND `To_UID` != '$userID'
    )
    UNION ALL
    (
    SELECT *, From_UID AS UID FROM `Messages` WHERE `To_UID` = '$userID' AND `From_UID` != '$userID'
    )
) AS A
ON A.UID = Users.ID
    GROUP BY UID // This doesn't work

如何只显示每个UID最多重新发送日期的行?

2 个答案:

答案 0 :(得分:1)

使用DISTINCT并仅使用ORDER BY date
GROUP BY实际上有时会显示一个随机行,但这并不常见。

答案 1 :(得分:0)

你可以尝试这样的事情:

select UID, Name, Text, c.date 
from User
inner join (
    select if(b.From_UID = '$userID', b.To_UID, b.From_UID) as UID, 
           * 
           from Messages as b 
           inner join(
               select if(c.From_UID = '$userID', c.To_UID, c.From_UID) as UID, 
                     max(c.date) as date 
                     from Messages as c
                     where c.From_UID = '$userID' or c.To_UID = '$userID' 
                     group by UID
            ) as d on d.date = b.date and d.UID = b.UID
     ) as e on e.UID = Users.id
)

或创建临时表/存储过程以使生活更轻松

临时表

create temp table t 
    select if(From_UID = '$userID', To_UID, From_UID) as UID, * from Messages


select UID, Name, Text, date
from User
inner join (
    select * 
        from t as t1
        inner join( 
            select 
                t2.UID, 
                max(t2.date) as date
                from t as t2
                group by t2.UID
         ) as t3 on t3.date =  t1.date and t3.UID = t1.UID
    ) as e on e.UID = Users.id