0

我正在使用一个 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 重新发送日期最多的行?

4

2 回答 2

1

useDISTINCT和 only useORDER BY date
GROUP BY实际上有时会显示随机行,这并不总是经常讨论的。

于 2012-08-18T03:22:57.787 回答
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     
于 2012-08-18T04:09:13.667 回答