使用联接不正确?

时间:2018-09-30 04:03:11

标签: sql sql-server

所以我似乎无法通过联接获得结果。我想知道我是在错误地连接这些表还是在做其他错误的事情。我看了看桌子,似乎是正确的。

USE AdventureWorks2016;

SELECT 
    C.CustomerID, P.FirstName, P.LastName, A.City, S.StateProvinceCode
FROM 
    Sales.Customer AS C 
JOIN 
    Person.BusinessEntityContact AS BC ON BC.PersonID = C.PersonID 
JOIN 
    Person.Person AS P ON P.BusinessEntityID = BC.BusinessEntityID
JOIN 
    Person.BusinessEntityAddress AS BA ON BA.BusinessEntityID = BC.BusinessEntityID
JOIN 
    Person.Address AS A ON A.AddressID = BA.AddressID
JOIN 
    Person.StateProvince AS S ON S.StateProvinceID = A.StateProvinceID

2 个答案:

答案 0 :(得分:1)

我认为您在将Person表加入BusinessEntityContact时出错。 根据您提供的查询,我认为您应该基于PersonId字段加入这些表。

string

答案 1 :(得分:1)

您正在尝试选择自己的业务联系客户,并且没有此类客户。我建议从查询中删除 BusinessEntityContact 表,然后尝试以下操作:

SELECT C.CustomerID, P.FirstName, P.LastName, A.City, S.StateProvinceCode
FROM Sales.Customer AS C 
  JOIN Person.Person AS P ON C.PersonID = P.BusinessEntityID 
    JOIN Person.BusinessEntityAddress AS BA ON P.BusinessEntityID = BA.BusinessEntityID 
      JOIN Person.Address AS A ON BA.AddressID = A.AddressID 
        JOIN Person.StateProvince AS S ON A.StateProvinceID = S.StateProvinceID