0

我不确定我是否以正确的方式进行此操作,因此我将不胜感激现实检查。两张桌子;用户和饲料。

+--------+-----------+----------+----------+
| userid | firstname | lastname | username |
+--------+-----------+----------+----------+
|     63 | Chris     | Smith    | csmith   |
|     65 | Roger     | Smith    | rsmith   |
|     66 | Diane     | Smith    | dsmith   |
+--------+-----------+----------+----------+

+-----------+--------+-----------+----------------+
| messageid | userid | contactid | subject        |
+-----------+--------+-----------+----------------+
|         4 | 67     | 63        | Test message 1 |
|         5 | 67     | 63        | Test message 2 |
|         6 | 63     | 67        | Test message 3 |
|         7 | 63     | 67        | Test message 4 |
|         8 | 65     | 66        | Test message 5 |
|         9 | 65     | 66        | Test message 6 |
|        10 | 66     | 65        | Test message 7 |
|        11 | 66     | 65        | Test message 8 |
+-----------+--------+-----------+----------------+

当我在用户页面上生成消息时,我需要在用户 ID(发起者)或联系人 ID(收件人)中的位置显示消息。将使用用户的用户 ID。但是,我需要显示用户的用户名,而不是他们的用户 ID。所以,这似乎是一个连接语句,我可以组合一个连接,将几乎所有这些信息汇集在一起​​。

select a.userid, b.username, a.contactid,
       a.subject, a.message, a.timestamp
from   feed as a,
       users as b
where a.userid=b.userid

结果:

+--------+----------+-----------+----------------+-------------------------------------+
| userid | username | contactid | subject        | message                             |
+--------+----------+-----------+----------------+-------------------------------------+
| 67     | Kimomaru | 63        | Test message 1 | This is a test, hello, hello, hello |
| 67     | Kimomaru | 63        | Test message 2 | This is a test, hello, hello, hello |
| 63     | csmith   | 67        | Test message 3 | This is a test, hello, hello, hello |
+--------+----------+-----------+----------------+-------------------------------------+

但是,我想在 contactid 之后添加一列,以显示收件人的用户名,该用户名来自用户表中的用户名列。我怎样才能做到这一点?

4

1 回答 1

1
select a.userid, b.username, a.contactid, 
       c.username, a.subject, a.message, a.timestamp 
from feed as a, users as b , users as c
where a.userid=b.userid and a.contactid=c.userid
于 2013-08-31T06:54:57.900 回答