关键字' join'附近的语法不正确

时间:2016-05-30 13:04:54

标签: sql sql-server-2005

我的以下查询导致错误:

  

关键字'加入'附近的语法不正确。

Select top 1 
    a.mkey, emp_received, a.mkey, 
    c.type_desc DOC_TYPE, a.doc_no INWARD_NO, 
    c.type_desc dept_received, c.type_desc EMP_RECEIVED,   
    convert(varchar, a.doc_date, 103) date,   
    a.to_user, a.No_of_pages, Ref_No, c.type_desc,   
    e.emp_name NAME, 
    ISNULL(e.Email_Id_Official, 'abc@test.com') EMAILID   
from 
    inward_doc_tracking_hdr a 
left join 
    type_mst_a c on a.doc_type = c.master_mkey 
                 and 
left join 
    type_mst_a c on a.dept_received = c.master_mkey 
left join 
    emp_mst e on a.emp_received = e.mkey  
where 
    a.emp_received is not null   
    and a.mkey = (select mkey 
                  from inward_doc_tracking_hdr aa 
                  where doc_no='IW/16/97')

我不知道它导致错误的原因

根据戈登的回答,我为emp_received添加了一个左连接,但它无法正常工作

Select top 1 a.mkey, 
            cd.type_desc as DOC_TYPE,  a.doc_no as INWARD_NO,
           cr.type_desc as DEPT_RECEIVED, qr.type_desc as EMP_RECEIVED,   
           convert(varchar(255), a.doc_date,103) as date,
           a.to_user, a.No_of_pages, Ref_No, 
           e.emp_name as NAME, 
           coalesce(e.Email_Id_Official, 'test@test.com') EMAILID   
    from inward_doc_tracking_hdr a left join
         type_mst_a cd
         on a.doc_type = cd.master_mkey left join
         type_mst_a cr     
         on a.emp_received = qr.master_mkey left join
         type_mst_a st
         on a.dept_received = cr.master_mkey left join
         emp_mst e
         on a.emp_received = e.mkey 
    where a.emp_received is not null and 
          a.mkey = (select mkey
                    from inward_doc_tracking_hdr aa
                    where doc_no = 'IW/16/97'
                   );

1 个答案:

答案 0 :(得分:3)

我认为您想要的查询更像是这样:

Select top 1 a.mkey,emp_received , 
       a.mkey, cd.type_desc as DOC_TYPE,  a.doc_no as INWARD_NO,
       cr.type_desc as dept_received, cr.type_desc as EMP_RECEIVED,   
       convert(varchar(255), a.doc_date,103) as date,
       a.to_user, a.No_of_pages, Ref_No, 
       e.emp_name as NAME, 
       coalesce(e.Email_Id_Official, 'test@test.com') as EMAILID   
from inward_doc_tracking_hdr a left join
     type_mst_a cd
     on a.doc_type = cd.master_mkey left join
     type_mst_a cr
     on a.dept_received = cr.master_mkey left join
     emp_mst e
     on a.emp_received = e.mkey 
where a.emp_received is not null and 
      a.mkey = (select mkey
                from inward_doc_tracking_hdr aa
                where doc_no = 'IW/16/97'
               );

注意:

  • 当前的问题是and left joinand导致语法错误。
  • 您有两个具有相同别名的表。这是不允许的。
  • 您需要注意哪些列来自哪些表;我做了个很好的猜测。
  • 每当在SQL Server中使用varchar()时,始终包含长度。默认长度因上下文而异,如果你很懒,你可能会在某些时候遇到难以调试的错误。
  • 定义列别名时使用as