在SQL Server中以相同条件连接两个表

时间:2015-12-07 05:06:09

标签: sql sql-server sql-server-2008 join

我有两张表cafedetailsemployeedetails

  • cafedetails列有cafemanagerid和staffid
  • employeedetails包含employeeid,employeename

我想了解详情

cafemanagerid, name, staffid, name

我的查询:

select 
    cafemanagerid, employeename as cafemanagerName, 
    staffid, employeename as staffname
from 
    cafedetails, employeedetails
where 
    cafemanagerid = employeeid 
    and staffid = employeeid 

我知道不工作但是如何实现这个目标?

帮帮我......

1 个答案:

答案 0 :(得分:0)

您需要加入employeedetails两次,每次都有不同的别名。 在这个例子中,我使用了一个完整的外连接来显示数据是否匹配。可能出现空值是另一个不存在。

SELECT 
    cd.cafemanagerid,
    cafe.employeename AS cafemanagerName,
    cd.staffid,
    staf.employeename AS staffname 
FROM 
    cafedetails AS cd
    FULL OUTER JOIN employeedetails AS cafe ON cd.cafemanagerid = cafe.employeeid
    FULL OUTER JOIN employeedetails AS staf ON cd.staffid = staf.employeeid

如果您想要两者都存在的行,请将FULL OUTER JOIN更改为INNER JOIN