2017-01-02 57 views
1

我一直在努力掙扎,這真的很複雜,所以請專注,因爲它很難解釋。MySQL ORDER BY不同的表格列,但

我有一個表朋友的列:

id, friend1, friend2, since 

我要顯示所有用戶的朋友從不同的表(表名用戶的活動下令:accinfo,列:lastact)其中lastact的值是一個php時間。

的問題是,我不知道哪個列是朋友......它可能或者是friend1friend2但是這取決於... 我怎麼能找出哪些列是朋友的名字,而不是名稱的用戶?我顯然需要在SQL本身中檢查它,以便讓最近活動排序的朋友。謝謝。

表:

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 
+0

能否請您分享這兩個表的一些示例數據? – 1000111

+0

@ 1000111 - 會做 –

回答

1

一種方法是有條件的加入:

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; 
+0

如果我想按照最後的順序排列它? –

+0

你在這裏有一些錯字,但它有效。謝謝。 –

1

試試這個,

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