如何在此创建sql语句,输出如此,我尝试了内连接,但我无法在usertable中获得p_id的名称。
user_id user_name p_name pid
1 millan null
5 jane millan 1
6 lester millan 1
7 miller jane 5
8 jamie jane 5
这是我的桌子。 的 gather_table
p_id u_id
null 1
1 5
1 6
5 7
5 8
用户表
user_id user_name
1 millan
2 john
3 max
4 chris
5 jane
6 lester
7 miller
8 jamie
提前谢谢。
答案 0 :(得分:3)
您需要加入user table
两次以获取名称
select
g.u_id,
u1.user_name,
u2.user_name as p_name,
g.p_id as pid
from gather_table g
left join user u1 on u1.user_id = g.u_id
left join user u2 on u2.user_id = g.p_id
答案 1 :(得分:1)
试试这个:
SELECT u1.user_id, u1.user_name, u2.user_name AS p_name, u2.user_id AS pid
FROM gather_table g
LEFT JOIN user_table u1 ON g.u_id = u1.user_id
LEFT JOIN user_table u2 ON g.p_id = u2.user_id