从内部查询中获取列

时间:2016-07-08 11:00:18

标签: sql sql-server

对下面的SQL有一些疑问:

SELECT mattyp.ID As mattypId, mattyp.Name As mattypName
FROM T_MaterialType as mattyp 
WHERE mattyp.ID IN                                      
      (SELECT mather_mattyp.FK_Material_Type_ID 
       FROM T_Material_T_Hersteller_T_MaterialType As mather_mattyp 
       WHERE mather_mattyp.FK_Material_Hersteller_ID IN 
             (SELECT mat_her.ID 
              FROM T_Material_T_Hersteller As mat_her
              INNER JOIN T_Material As mat ON mat_her.FK_Material_ID = mat.ID
              INNER JOIN T_Hersteller As her ON mat_her.FK_Hersteller_ID = her.ID  
              WHERE mat_her.FK_Hersteller_ID = 29 
                AND mat_her.ID IN
                    (SELECT FK_MaterialHersteller_ID 
                     FROM T_MaterialHersteller_KatSub_SubSubKat 
                     WHERE FK_KatSubKat_ID = 249 )))--AND (FK_Subsubkat_ID = 91 OR FK_Subsubkat_ID IS NULL))))

正如你在最上面看到的那样,我采用了这些专栏:

mattyp.ID As mattypId, mattyp.Name As mattypName

但是在整个SQL中,我还想采取:

Name field from table mat (T_Material) and Name field from her (T_Hersteller).

我怎样才能实现这一目标?目前,当我在顶部这样做时:

SELECT mattyp.ID As mattypId, mattyp.Name As mattypName, mat.Name, her.Name

我收到此错误消息:

  

Msg 4104,Level 16,State 1,Line 47
  多部分标识符" mat.Name"无法受约束。

     

Msg 4104,Level 16,State 1,Line 47
  多部分标识符" her.Name"无法受约束。

我是这样做的,但我不确定这是不是错,有人可以查一下吗?:

SELECT mattyp.ID As mattypId, mattyp.Name As mattypName, mat.Name, her.Name
FROM T_MaterialType as mattyp
INNER JOIN T_Material_T_Hersteller_T_MaterialType As mather_mattyp ON mattyp.ID = mather_mattyp.FK_Material_Type_ID 
INNER JOIN T_Material_T_Hersteller As mat_her ON mather_mattyp.FK_Material_Hersteller_ID = mat_her.ID
INNER JOIN T_Material As mat ON mat_her.FK_Material_ID = mat.ID
INNER JOIN T_Hersteller As her ON mat_her.FK_Hersteller_ID = her.ID  
WHERE mat_her.FK_Hersteller_ID = 29 
  AND mat_her.ID IN
      (SELECT FK_MaterialHersteller_ID 
       FROM T_MaterialHersteller_KatSub_SubSubKat  
       WHERE FK_KatSubKat_ID = 249 )--AND (FK_Subsubkat_ID = 91 OR FK_Subsubkat_ID IS NULL))))

1 个答案:

答案 0 :(得分:0)

试试这个,这将得到与IN条件的原始查询相同的结果。

SELECT DISTINCT
    mattyp.ID As mattypId, 
    mattyp.Name As mattypName, 
    mat.Name, 
    her.Name
FROM T_MaterialType as mattyp 
INNER JOIN T_Material_T_Hersteller_T_MaterialType As mather_mattyp ON mather_mattyp.FK_Material_Type_ID = mattyp.ID
INNER JOIN T_Material_T_Hersteller As mat_her ON mather_mattyp.FK_Material_Hersteller_ID = mat_her.ID 
    AND mat_her.FK_Hersteller_ID = 29 
INNER JOIN T_Material As mat ON mat_her.FK_Material_ID = mat.ID
INNER JOIN T_Hersteller As her ON mat_her.FK_Hersteller_ID = her.ID  
INNER JOIN T_MaterialHersteller_KatSub_SubSubKat mat_katsub ON mat_katsub.FK_MaterialHersteller_ID = mat_her.ID
    AND mat_katsub.FK_KatSubKat_ID = 249