1

我猜这对于实验过的 Sql 用户来说非常容易:

给出下表:

表用户

   id  Name
   1 | Stephan
   2 | Marion
   3 | Jonathan
   4 | Morgan

表消息

  id| sender | reveiver | message
   1|    2   |     4    | "hello world!"

您将如何请求获得以下内容(仅在一个 sql 请求中):

 id| sender | reveiver | message        | sender.username | receiver.username
  1|    2   |     4    | "hello world!" |       Marion    |        Morgan

非常感谢!

4

4 回答 4

2

尝试

select m.id, sender, receiver, message, sender.name, receiver.name
from messages m
left outer join users sender on sender.id = m.sender
left outer join users receiver on receiver.id = m.receiver
于 2012-07-24T13:36:28.993 回答
1
SELECT
    m.id
    , m.sender
    , m.receiver
    , m.message
    , s.name
    , r.name
FROM
    messages m
    , INNER JOIN names s ON (s.id = m.sender)
    , INNER JOIN names r ON (r.id = m.receiver)
于 2012-07-24T13:37:37.067 回答
1
    select
        m.id
    ,  m.sender
    ,  m.receiver
    ,  m.message
    ,  su.user
    ,  ru.user
    from message m
    join user su on (su.id = m.sender)
    join user ru on (ru.id = m.receiver)

我确信有一种更有效的方法,但这可能是最简单的。

于 2012-07-24T13:39:07.683 回答
1
select m.id, sender, reveiver, message,
  sender.Name as sender_username, receiver.Name as receiver_username
from messages m
inner join users sender on sender.id = m.sender
inner join users receiver on receiver.id = m.reveiver
于 2012-07-24T13:50:05.750 回答