[英]Order by multiple tables column
我想運行一個查詢,該查詢將根據另一個表的列中的值(如果存在)對我的數據進行排序,如果另一個列中不存在數據,則應按當前表中存在的列對其進行排序。
說明:-
成員表:包含所有成員的列表。
消息表:存儲兩個成員之間的聊天對話
From_ID is basically sender id
To_ID is basically recipient id
如果成員1002登錄到應用程序,我要從成員表中檢索所有用戶的列表,順序是它首先應包含與成員1002最近在消息表中進行過對話(發送或接收)的那些用戶,然后從成員表中包含其他用戶。
表:成員
id name
1001 john
1002 vicky
1003 Joseph
1004 Donald
1005 David
1006 Ram
1007 Watson
1008 Jacob
1009 cathrine
表:消息
from_id to_id date
1003 1009 21-01-2018
1007 1002 21-01-2018
1008 1001 02-01-2018
1002 1008 01-01-2018
select *
from members
where id = '1002' order by (messages????????);
結果:輸入id 1002
Desired output:
1007
1008
1001
1003
1004
1005
1006
1009
您首先要用戶1002的最近對話伙伴。 最簡單的方法是按最新消息日期訂購:
select *
from members m
where id <> 1002
order by
(
select max(ms.date)
from messages ms
where (ms.from_id = m.id and ms.to_id = 1002)
or (ms.from_id = 1002 and ms.to_id = m.id)
) desc nulls last;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.