我有这个问题:
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);
结果如下:
我还有一个包含名字的表。像这样:
// users
+------+_--------+
| id | name |
+------+---------+
| 1246 | Jack |
| 1247 | Peter |
| 1246 | Ali |
| . | . |
| . | . |
| . | . |
+------+---------+
现在我希望在输出中获得名称而不是 ID 。注意user_id
和friend_id
都引用了users
表。我怎么能这样做?
答案 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);