0

これが正しい方法であるかどうかはわかりませんので、現実を確認していただければ幸いです。2 つのテーブル。ユーザーとフィード。

+--------+-----------+----------+----------+
| 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 |
+-----------+--------+-----------+----------------+

ユーザーのページでメッセージを作成する場合、メッセージが userid (発信者) または 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 の後に列を追加したいと思います。これどうやってするの?

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 に答える