如何从这个多对多表中进行选择

时间:2017-03-22 19:42:17

标签: mysql sql

数据库:mySQL

我正在寻找的是:一种选择状态X与用户X的用户列表的方法。让我们说我的名字是詹姆斯,我想得到我的朋友列表。这可能吗?

表格用户:
- ID
- first_name
- last_name
...

Tabel User_Status:
- User_ID1
- User_ID2
- 状态

我想要的结果应该是这样的:让我的用户ID = 0。

User_ID1 ----- ----- User_ID2状态
------ 0 --------------- 1 -----------朋友
------ 0 --------------- 2 -----------朋友
------ 0 --------------- 3 -----------朋友
------ 0 --------------- 4 -----------朋友
------ 0 --------------- ----------- 5朋友

1 个答案:

答案 0 :(得分:1)

mysql> select * from User;
+----+------------+-----------+
| ID | first_name | last_name |
+----+------------+-----------+
|  1 | Nikolai    | Tesla     |
|  2 | Albert     | Einstein  |
|  3 | Bertrand   | Russell   |
|  4 | Carl       | Sagan     |
+----+------------+-----------+
4 rows in set (0.00 sec)

mysql> select * from User_Status;                                                                    +----------+----------+---------------+
| User_ID1 | User_ID2 | Status        |
+----------+----------+---------------+
|        1 |        2 | FRIENDS       |
|        1 |        3 | FRIENDS       |
|        2 |        1 | FRIENDS       |
|        3 |        4 | ACQUAINTANCES |
|        3 |        1 | FRIENDS       |
+----------+----------+---------------+

mysql> SELECT u.* 
       FROM User u   
       JOIN User_Status us ON u.ID = us.User_ID1 
       WHERE us.Status = "FRIENDS" AND us.User_ID2 = 1;
+----+------------+-----------+
| ID | first_name | last_name |
+----+------------+-----------+
|  2 | Albert     | Einstein  |
|  3 | Bertrand   | Russell   |
+----+------------+-----------+
2 rows in set (0.00 sec)