SQL查询从表中获取多次信息

时间:2012-07-24 13:32:33

标签: php sql

对于我猜测的实验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 个答案:

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

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

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

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

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