订购多个列

时间:2015-06-05 20:35:21

标签: mysql sql

我有一个表msg(ID,TO,FROM,MSG,TIME),我需要从TO和FROM中选择不同的元组,并根据消息发送的最新时间对结果进行排序。我用过的查询

SELECT DISTINCT value 
FROM ( SELECT msg.to AS value, time 
        FROM msg 
        WHERE msg.from = '".$_SESSION["username"]."' 
    UNION 
        SELECT msg.from AS value, time 
        FROM msg 
        WHERE msg.to = '".$_SESSION["username"]."') TT 
order by time desc

并且

select t1.to, t1.time 
from msg t1 
where t1.from='".$_SESSION["username"]."' 
    and t1.time=(
        select max(time) 
        from msg t2 
        where t2.to=t1.to) 
union 
select t1.from, t1.time 
from msg t1 
where t1.to='".$_SESSION["username"]."' 
    and t1.time=(
        select max(time) 
        from msg t2 
        where t2.from=t1.from)

但是没有人给出结果。

2 个答案:

答案 0 :(得分:0)

“理想的结果”是什么?它与以下有什么不同?

select TO, FROM, max(TIME) as TIME
from msg
group by TO, FROM
order by max(TIME) desc

答案 1 :(得分:0)

SELECT value, max(time) as latest_time_sent
FROM ( SELECT msg.to AS value, time 
        FROM msg 
        WHERE msg.from = '".$_SESSION["username"]."' 
    UNION ALL
        SELECT msg.from AS value, time 
        FROM msg 
        WHERE msg.to = '".$_SESSION["username"]."') TT 
group by value
order by latest_time_sent desc