0

我有 3 个表:
user(use_id, use_role),
message(mes_id, from_use_id[fk->user.use_id], mes_create_at),
message_user(mes_use_id, mes_id[fk->message.mes_id], to_use_id[fk->user.使用_id])

用户可以是 use_role=1(学生)或 use_role=2(教师)。
我必须让所有 use_type=1(student) 的用户按与老师的最后一次联系进行排序。不管是学生给老师写信还是老师给学生写信。

4

1 回答 1

0

我假设你使用 ms sql:

select *
from
(
    select student.use_id, Message.mes_create_at, Message.from_use_id, Message_User.to_use_id
    from User student
    join Message on Message.use_id = student.use_id and student.use_role = 1
    join Message_User on Message_User.mes_id = Message.mes_id
    where Message_User.to_use_id in (select use_id from User where use_role = 2)

    union

    select Message_User.to_use_id, Message.mes_create_at, Message.from_use_id, Message_User.to_use_id
    from User teacher
    join Message on Message.use_id = teacher.use_id and teacher.use_role = 2
    join Message_User on Message_User.mes_id = Message.mes_id
    where Message_User.to_use_id in (select use_id from User where use_role = 1)
) as temp
order by mes_create_at desc
于 2013-09-13T19:19:20.070 回答