Mysql:帮助查询两个表

时间:2014-05-18 19:29:51

标签: mysql sql

我有两个表:用户,这样结构的朋友:

用户:

+------------+--------------+.  
| users_id   | username     |.  
+------------+--------------+.  
| 1          | Mark         |.  
| 2          | Alex         |.  
| 3          | Anna         |.  
+------------+--------------+.  

朋友们:

+------------+--------------+.  
| id |fromid |  toid        |.  
+------------+--------------+.  
| 1  |    2  |     3        |.  
| 2  |    1  |     2        |.  
| 3  |    1  |     3        |.  
+------------+--------------+.   

检索这些结果的查询是什么:

+------------+--------------+.  
| from       |     to       |    
+------------+--------------+.  
| Alex       | Anna         |    
| Mark       | Alex         |.  
| Mark       | Anna         |.  
+------------+--------------+.        

P.s。:如果表格在我的问题中没有正确格式化,请原谅我

1 个答案:

答案 0 :(得分:0)

SELECT u1.name as from_name,
       u2.name as to_name
FROM Friends AS f
JOIN Users AS u1 ON u1.users_id = f.fromid
JOIN Users AS u2 ON u2.users_id = f.toid

这样做。