调用位于两个表中的列

时间:2016-10-25 15:15:27

标签: sql sql-server

我正在尝试获取CustomerID并且我一直收到错误消息。这是我的代码:

SELECT CustomerID, FirstName, LastName,Line1,Line2, City, State, ZipCode
FROM Customers INNER JOIN Addresses
    ON Customers.CustomerID = Addresses.CustomerID;

我的错误是:不明确的列名'CustomerID'。 当我使用JOIN语句时,怎么会这样呢?有什么想法吗?

3 个答案:

答案 0 :(得分:1)

使用别名:

SELECT C.CustomerID, C.FirstName, C.LastName, A.Line1, A.Line2, A.City, A.State, A.ZipCode
FROM Customers C
INNER JOIN Addresses A
        ON C.CustomerID = A.CustomerID;

答案 1 :(得分:0)

结果中有两列名为" CustomerID",因此SQL Server不知道您的意思。您在en-us.wxl中指定它们是平等的并不重要。 SQL仍需要您指定所需的那个。

您只需将表名添加到列中,但我更喜欢表别名:

JOIN

答案 2 :(得分:0)

您必须告诉数据库引擎从连接中显示哪个costumerID。

SELECT **Addresses.CustomerID**, FirstName, LastName,Line1,Line2, City, State, ZipCode 
FROM Customers 
INNER JOIN Addresses ON Customers.CustomerID = Addresses.CustomerID

SELECT **Customers.CustomerID**, FirstName, LastName,Line1,Line2, City, State, ZipCode 
FROM Customers 
INNER JOIN Addresses ON Customers.CustomerID = Addresses.CustomerID