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

消息表(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 回答