SQL查询:连接+条件+顺序

时间:2013-09-13 18:44:00

标签: sql

我有3张桌子:
user(use_id,use_role),
消息(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.use_id])

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

1 个答案:

答案 0 :(得分: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