我不确定我是否会采用正确的方式,所以我很欣赏现实检查。两张桌子;用户和Feed。
+--------+-----------+----------+----------+
| 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(创建者)或contactid(接收者)中显示消息。将使用用户的用户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之后添加一个列,显示收件人的用户名,该用户名将来自用户表中的用户名列。我怎么能这样做?
答案 0 :(得分: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