我需要一些 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 |
+---------+----------+------------+
消息表(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 |
+----------+------------+