0

我有以下表格:

学生们

StudentID     UserID     FirstName     LastName
1             1          John          Doe
2             3          Peter         Pan
3             5          Mark          Twain

雇员

EmployeeID     UserID     FirstName     LastName
1              2          Juan          Carlos
2              4          Joe           Reyes
3              6          Ash           Ketchum

用户

UserID     Username
1          test1
2          test2
3          test3
4          test4
5          test5
6          test6

留言

MessageID     MessageFrom     MessageTo     Subject
1             1               2             test message
2             4               3             another test message
3             3               5             another test message

我想像这样显示输出

MessageID     MessageFrom     MessageTo     Subject
1             John Doe        Juan Carlos   test message
2             Joe Reyes       Peter Pan     another test message
3             Peter Pan       Mark Twain    another test message

WhereMessageFrom并返回来自用户表MessageTo的外键值。UserID学生可以向员工发送消息,反之亦然。他们还可以在学生和员工之间发送。

4

2 回答 2

2

我认为这又是XY 问题

你为什么把你Users的分成两部分?

为什么不这样做(这将解决整个问题):

UserID  |   FirstName   |  LastName | UserName |  Type
-------------------------------------------------------
  1           John          Doe        test1       1
  2           Juan          Carlos     test2       2
  3           Mark          Twain      test3       1

并添加一个表类型

TypeId  |   TypeName

  1          Students
  2          Employees

这样,您就有 2 个用户表,而不是 3 个。所有用户和名称都在同一个表中,因为它应该是

于 2012-07-27T16:00:06.467 回答
1

这应该可以解决问题,因为您不在乎消息是否与学生或员工有关,您可以将这两个表合并。

SELECT 
    MessageID,
    (FromTable.FirstName + ' ' + FromTable.LastName) AS MessageFrom,
    (ToTable.FristName + ' ' + ToTable.LastName) AS MessageTo,
    Subject
FROM
    Messages
    INNER JOIN
    (
        (SELECT UserID, FirstName, LastName FROM Students)
        UNION 
        (SELECT UserID, FirstName, LastName FROM Employees)
    ) AS FromTable ON FromTable.UserID = Messages.MessageFrom
    INNER JOIN
    (
        (SELECT UserID, FirstName, LastName FROM Students)
        UNION 
        (SELECT UserID, FirstName, LastName FROM Employees)
    ) AS ToTable ON ToTable.UserID = Messages.MessageTo
于 2012-07-27T15:56:10.137 回答