INNER JOIN + LEFT JOIN的SQL错误

时间:2017-10-25 15:54:45

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

我正在尝试查询数据在4个表中的位置:

TAFCBHISTPED = NUPED, DTEMIS

TAFGRPROD = CDGRPR, DSGRPR

TAFPROD = CDPROD, CDGRPR

TAFITHISTPED = NUPED, CDPROD, QTPED

我当前的查询如下所示:

SELECT
   TAFCBHISTPED.NUPED,
   TAFCBHISTPED.DTEMIS,
   TAFGRPROD.CDGRPR,
   TAFGRPROD.DSGRPR,
   TAFPROD.CDPROD,
   TAFPROD.CDGRPR,
   TAFITHISTPED.NUPED,
   TAFITHISTPED.CDPROD,
   TAFITHISTPED.QTPED
FROM
   dbo.TAFCBHISTPED -- table1
INNER 
JOIN dbo.TAFITHISTPED -- table2
ON TAFCBHISTPED.NUPED = TAFITHISTPED.NUPED
LEFT 
JOIN dbo.TAFPROD -- table3
  ON TAFGRPROD.CDGRPR = TAFPROD.CDGRPR

但是我收到以下错误:

SQLState: 42000 Error Code: 4104 Message: 
[Microsoft] [ODBC Driver 13 for SQL Server] [SQL Server] 
The multipart identifier "TAFGRPROD.CDGRPR" can not be associated.

2 个答案:

答案 0 :(得分:1)

你没有与TAFGRPROD表的关系

SELECT
   TAFCBHISTPED.NUPED,
   TAFCBHISTPED.DTEMIS,
   TAFGRPROD.CDGRPR,
   TAFGRPROD.DSGRPR,
   TAFPROD.CDPROD,
   TAFPROD.CDGRPR,
   TAFITHISTPED.NUPED,
   TAFITHISTPED.CDPROD,
   TAFITHISTPED.QTPED
FROM TAFCBHISTPED
INNER JOIN dbo.TAFITHISTPED ON 
TAFCBHISTPED.NUPED = TAFITHISTPED.NUPED

--CHECK THE REFERENCE FIELDS
LEFT JOIN dbo.TAFGRPROD ON 
    TAFCBHISTPED.CDGRPR = TAFGRPROD.CDGRPR

LEFT JOIN dbo.TAFPROD ON 
TAFGRPROD.CDGRPR = TAFPROD.CDGRPR

答案 1 :(得分:0)

要连接表,您需要有适当的关系。下图说明了SQL中可用的连接 enter image description here

表2和表3没有关系,因此连接将失败。 SQL链接的有用教程。 http://www.sql-join.com/sql-join-types/