SQL - 左连接中的表别名

时间:2017-05-29 08:04:10

标签: sql left-join table-alias

我正在尝试使用Left Join编写一个简单的SQL查询。

这是查询:

SELECT * 
FROM ( 
   SELECT * 
   FROM TRN_IN.COIT AS TRANSMISSIONS
     LEFT JOIN ( 
       SELECT TRNNumber ,COUNT(ID) 
       FROM TRN_IN.COIT AS TOTAL_LINES   
       WHERE DataPiece02 = 'TO'   
       GROUP BY TRNNumber 
   ) ON TRANSMISSIONS.TRNNumber  = TOTAL_LINES.TRNNumber
)

第二个表别名是TOTAL_LINES。

运行时,我收到一个错误,即未列出TOTAL_LINES。

奇怪的是,当尝试自己运行第二个查询时,没有错误:

(SELECT TRNNumber ,COUNT(ID) 
 FROM TRN_IN.COIT AS TOTAL_LINES 
 WHERE DataPiece02 = 'TO' 
 GROUP BY TRNNumber )

有人有线索吗?

3 个答案:

答案 0 :(得分:3)

希望您在错误的位置分配AS TOTAL_LINES表别名。

在第二个子查询后放置表别名将解决您的问题。

您可以尝试以下查询:

SELECT *
FROM (
    SELECT *
    FROM TRN_IN.COIT AS TRANSMISSIONS
    LEFT JOIN (
        SELECT TRNNumber
            ,COUNT(ID) AS CountDetails
        FROM TRN_IN.COIT 
        WHERE DataPiece02 = 'TO'
        GROUP BY TRNNumber
        ) AS TOTAL_LINES ON TRANSMISSIONS.TRNNumber = TOTAL_LINES.TRNNumber
    ) AS Result

答案 1 :(得分:1)

TOTAL_LINES必须是整个select的别名,而不是from子句中的表。改为:

SELECT * FROM ( SELECT * FROM TRN_IN.COIT AS TRANSMISSIONS

LEFT JOIN ( SELECT TRNNumber ,COUNT(ID) FROM TRN_IN.COIT WHERE DataPiece02 = 'TO'   GROUP BY TRNNumber ) AS TOTAL_LINES   

ON TRANSMISSIONS.TRNNumber  = TOTAL_LINES   .TRNNumber)

答案 2 :(得分:1)

试试这个..

SELECT TOTAL_LINES.TRNNumber,COUNT(TOTAL_LINES.ID) FROM TRN_IN.COIT TRANSMISSIONS LEFT JOIN TRN_IN.COIT TOTAL_LINES 
ON TRANSMISSIONS.TRNNumber  = TOTAL_LINES.TRNNumber
WHERE TOTAL_LINES.DataPiece02 = 'TO'   GROUP BY TOTAL_LINES.TRNNumber;