在同一查询中执行2个内部联接时出错

时间:2011-12-29 19:33:15

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

我正在做两个内部联接:

use SalesDWH
go


select COUNT([specimen id])  as [count],[practice name],qlmlismapping.[mlis practice id],[practice code],[Requesting Physician]
from quicklabdump a
inner join qlmlismapping b
on (b.[quiklab practice code] = a.[practice code])
inner join PracticeandPhysician c
on (a.[Requesting Physician]=c.doctorfirstname+' '+c.DOCTORLASTNAME)
where [DATE entered] between '12/1/2011' and '12/31/2011'
group by quicklabdump.[practice name],qlmlismapping.[mlis practice id],[practice code],[Requesting Physician]
order by [count] desc

并收到此错误:

Msg 4104, Level 16, State 1, Line 10
The multi-part identifier "quicklabdump.practice name" could not be bound.
Msg 4104, Level 16, State 1, Line 10
The multi-part identifier "qlmlismapping.mlis practice id" could not be bound.
Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "qlmlismapping.mlis practice id" could not be bound.

我做错了什么?连接不正确吗?

2 个答案:

答案 0 :(得分:4)

您无法在查询的其余部分中引用qlmlismapping等,因为您已使用别名隐藏它,因此这不是公开的相关名称。

除了实际定义别名之外,您需要在任何地方使用别名而不是基表名。

答案 1 :(得分:4)

使用与JOIN相同的别名

select 
       COUNT([specimen id]) as [count],
       [practice name],
       b.[mlis practice id],
       [practice code],
       [Requesting Physician]
from 
     quicklabdump a
     inner join 
     qlmlismapping b on (b.[quiklab practice code] = a.[practice code])
     inner join 
     PracticeandPhysician c on (a.[Requesting Physician]=c.doctorfirstname+' '+c.DOCTORLASTNAME)
where 
     [DATE entered] between '12/1/2011' and '12/31/2011'
group by 
     a.[practice name], 
     b.[mlis practice id],
     [practice code],
     [Requesting Physician]
order by 
     [count] desc

虽然有些注意事项

  • 限定所有列
  • 使用有意义的别名(qld,qlm,pap等)
  • 使用ISO日期yyyymmdd
  • 尝试使用不带空格的列名