MySQL ORDER BY 不同的 table 列但是

MySQL ORDER BY different table column but

我一直在努力解决这个问题,它真的很复杂,所以请集中注意力,因为它甚至很难解释。

我有一个 table 朋友 列:

id, friend1, friend2, since

我想显示所有 用户的 好友,该用户的 activity 从不同的 table 订购(table 姓名:accinfo,列:lastact) 其中 lastact 的值是 php 时间。

问题是我不知道哪一列是朋友...它可能是 friend1friend2 但这取决于... 我怎么能找出哪一列是朋友的名字而不是用户的名字?我显然需要在 SQL 本身中检查它,以便通过最新的 activity 整理出朋友。谢谢。

表格:

friends

id | friend1 | friend2 | since

1  | bob     | joe     | null
2  | kate    | jane    | null
3  | bob     | robby   | null


accinfo

id | username | lastact 

1  | bob      | 1483323711
2  | joe      | 1483323701
3  | kate     | 1483323642
4  | jane     | 1483311256
5  | robby    | 1483321234

一种方法是条件连接:

select f.*, ai.lasact
from friends f join
     accinfo ai
     on (ai.userid = f.friend1 and friend2 = $userid) or
        (ai.userid = f.friend2 and friend1 = $userid)
where $userid in (f.friend1, f.friend2)
order by lastacct desc;

试试这个,

SELECT acf.username FROM friends fds, accinfo acf WHERE (acf.username=fds.friend1 OR acf.username=fds.frien2) ORDER BY acf.lastact DESC