SQL左连接返回奇怪的ID

时间:2016-11-08 16:28:41

标签: sql sql-server tsql

我在SQL Server数据库中运行此SQL查询,

SELECT staff_list.id AS staff_id, 
       staff_list.status,  
       core_teams.workbase, 
       core_teams.service_user, 
       core_teams.staff_name,  
       core_teams.role, 
       service_users.id AS su_id  
FROM staff_list  
     LEFT JOIN core_teams   
       ON staff_list.workbase = core_teams.workbase  
     LEFT JOIN service_users
       ON service_users.name = core_teams.service_user
WHERE staff_list.status <> 'Left' 
     AND staff_list.status <> 'Name Changed';

正在返回联接和结果,但是对于与staff_id相关的用户,属性staff_id会在多行上重复多次。我做错了吗?

1 个答案:

答案 0 :(得分:0)

您可能缺少staff_list和core_teams之间的链接。

SELECT staff_list.id AS staff_id, staff_list.status,  
core_teams.workbase, core_teams.service_user, core_teams.staff_name,  
core_teams.role, service_users.id AS su_id  
FROM staff_list  
LEFT JOIN core_teams   
 ON staff_list.workbase = core_teams.workbase  
     --missing link
     AND staff_list.name = core_teams.staff_name
LEFT JOIN service_users
 ON service_users.name = core_teams.service_user   
WHERE staff_list.status <> 'Left' 
 AND staff_list.status <> 'Name Changed';