0

SQLのアドバイスが必要です。この問題を解決するための最良の方法(SQL結合やサブクエリを利用する)は何ですか?前もって感謝します :)

users TABLE (user_id = Primary Key)
+---------+----------+------------+
| user_id |   name   |   surname  |
+---------+----------+------------+
| 001     | Tangi    | Amalenge   |
| 002     | John     | Doe        |
| 003     | Sally    | Angula     |
| 004     | Simon    | v Wyk      |
| 005     | Nangula  | Abed       |
+---------+----------+------------+

messages TABLE(message_id=主キー;user1&user2 = users.user_idを参照する外部キー)

+------------+----------+------------+----------------+
| message_id |  user1   |   user2    |  date_created  |
+------------+----------+------------+----------------+
|   101      |   001    |    003     |  2012-05-20    |
|   102      |   002    |    001     |  2012-05-18    |
|   103      |   003    |    005     |  2012-05-18    |
|   104      |   005    |    002     |  2012-05-17    |
|   105      |   001    |    004     |  2012-05-09    |
+------------+----------+------------+----------------+
I would like to retrieve the names and the id of the message I 
share with a user. My user_id is 001.
If I'm user1 in the messages TABLE, then I want to know who user2 is, and if I'm user2,
I want to know who user1 is, plus the id of the message we share.
Like this:
+----------+------------+
|   name   | message_id |
+----------+------------+
| Sally    | 101        |
| John     | 102        |
| Tangi    | 105        |
+----------+------------+
4

2 に答える 2

1

これを試して:

SELECT u.name, m.message_id
FROM users u, messages m
WHERE (m.user1 = u.user_id AND m.user2 = "001")
   OR (m.user2 = u.user_id AND m.user1 = 001)
于 2012-05-25T12:33:05.037 に答える
0
Select u.name, m1.message_id from users u 
inner join messages m1
On m1.user1 = u.user_id
Inner join Messages m2
On m2.user2=u.user_id
Where m1.user1='001' or m2.user2='001'

これがお役に立てば幸いです。

于 2012-05-25T13:39:32.370 に答える