如何通过他的ID获取每个用户的名字?

时间:2017-02-01 06:46:24

标签: mysql sql

我有这个问题:

SELECT DISTINCT p1.rootid AS user_id, p1.rid AS friend_id
 FROM relations p1
WHERE rootid = 1246
   OR rootid IN (SELECT p2.rid
              FROM relations p2
              WHERE rootid = 1246);

结果如下:

enter image description here

我还有一个包含名字的表。像这样:

// users
+------+_--------+
|  id  |  name   |
+------+---------+
| 1246 | Jack    |
| 1247 | Peter   |
| 1246 | Ali     |
| .    | .       |
| .    | .       |
| .    | .       |
+------+---------+

现在我希望在输出中获得名称而不是 ID 。注意user_idfriend_id都引用了users表。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

尝试这样的事情,

SELECT u1.name user_name, u2.name friend_name from relations r
INNER JOIN users u1 ON u1.id = r.user_id
INNER JOIN users u2 ON u2.id = r.friend_id
where r.user_id = 1246

希望这能解决您的问题。

答案 1 :(得分:0)

试试这个:

SELECT DISTINCT  u.name AS user_name, f.name AS friend_name
 FROM relations p1
 INNER JOIN user u ON u.id = p1.rootid
 INNER JOIN user f ON f.id = p1.rid
WHERE rootid = 1246
   OR rootid IN (SELECT p2.rid
              FROM relations p2
              WHERE rootid = 1246);