问题
I have three tables:
Message_Threads: ( thread_ID )
Message_Users: ( thread_ID, user_ID, notify )
Messages: ( thread_ID, user_ID, message_ID, date_created )
I am trying to list out just the threads in order of most recent message within the thread, but I want to show the ones that have notify=1 above the rest (notify is set to 1 for all other users on a thread when a new message is posted and set to 0 when they visit that thread). Anyone got a monster select statement for me?
回答1:
Your data structure does not make clear the relationship be messages and message user. My assumption is that these are joined on both thread_id and user_id. This then aggregates them at the thread level:
select t.thread_id
from thread t join
message m
on t.thread_id = m.thread_id join
message_users mu
on m.thread_id = mu.thread_id and
m.user_id = mu.user_id
group by thread_id
order by max(mu.notify) desc, max(m.date_created) desc
The key to this is the final order by. Order by notify first, but descending so "1" appears before "0" (assuming non-1 value is 0). Then by date created.
To restrict this to a particular user, use a WHERE statement before the group by:
WHERE u.user_id = session_user_id
来源:https://stackoverflow.com/questions/12058902/sql-order-by-threads-messages