在SQL Server 2008中,我有两个表。一个用户表:
id_user - integer, primary key
id_group - integer
username - varchar
phone - varchar
id_coordinating - int
示例数据:
1, 1, admin, 0230029921, NULL
2, 2, supervisor1, 0230029933, NULL
3, 2, supervisor2, 0321211233, NULL
4, 3, user1, 0321222323, 2
5, 3, user2, 0323211232, 2
6, 3, user3, 0324223121, 3
组USERS中的所有用户都有一个由id_user
另一个小组表
id_group - integer, primary key
groupname - varchar
示例数据:
1, Administrators
2, Supervisors
3, Users
我正在运行以下查询:
select id_user, username, group.groupname, phone, id_coordinating
from users
INNER JOIN group ON users.id_group = group.id_group
我得到以下结果:
1 1 admin Administrators 0230029921 NULL
2 2 supervisor1 Supervisors 0230029933 NULL
3 2 supervisor2 Supervisors 0321211233 NULL
4 3 user1 Users 0321222323 2
5 3 user2 Users 0323211232 2
6 3 user3 Users 0324223121 3
我想用用户名替换id_coordonating
,看起来像这样......
1 1 admin Administrators 0230029921 NULL
2 2 supervisor1 Supervisors 0230029933 NULL
3 2 supervisor2 Supervisors 0321211233 NULL
4 3 user1 Users 0321222323 supervisor1
5 3 user2 Users 0323211232 supervisor1
6 3 user3 Users 0324223121 supervisor2
谢谢,
答案 0 :(得分:0)
您可以left join
返回您的用户表格。
select
u.id_user,
u.username,
g.groupname,
u.phone,
u2.username
from users u
join group g
on u.id_group = g.id_group
left join users u2
on u.id_coordinating = u2.id_user