使用LEFT JOIN连接两个MSSQL数据库(在同一台服务器上)时遇到了很大的问题。我从数据库OLAB_DB运行此SQL并获取错误:
The multi-part identifier "OLAP_DB.dbo.OLAP_invoice.UserID" could not be bound.
DB似乎无法找到自己的问题,我不知道如何解决这个问题。我有两次和三次检查拼写并重写SQL几次,但现在我只需要放弃并寻求帮助:(
这不起作用:
SELECT TOP 200
COALESCE(LTRIM(RTRIM(contact_db.dbo.ContactTable.EmailAdr)),LTRIM(RTRIM(contact_db.dbo.CustomerTable.EmailAdr))) AS EMAIL,
OLAP_invoice.OrdreLinjeID AS ORDERNO
OLAP_invoice.SalgsPris AS PRICE,
OLAP_invoice.UserID AS CONTACTID
FROM OLAP_invoice,contact_db.dbo.CustomerTable
LEFT JOIN contact_db.dbo.ContactTable
ON OLAP_DB.dbo.OLAP_invoice.UserID = contact_db.dbo.ContactTable.UserID
WHERE contact_db.dbo.CustomerTable.ClientID = OLAP_invoice.ClientID
但跳过左连接只是从两个不同的数据库中获取数据就可以了。
这很好用:
SELECT TOP 200
LTRIM(RTRIM(contact_db.dbo.CustomerTable.EmailAdr)) AS EMAIL,
LTRIM(RTRIM(contact_db.dbo.ContactTable.UserID)) AS EMAIL2,
OLAP_invoice.OrdreLinjeID AS ORDERNO
OLAP_invoice.SalgsPris AS PRICE,
OLAP_invoice.UserID AS CONTACTID
FROM OLAP_invoice,contact_db.dbo.CustomerTable
WHERE contact_db.dbo.CustomerTable.ClientID = OLAP_invoice.ClientID
AND contact_db.dbo.ContactTable.UserID = OLAP_invoice.UserID
我需要LEFT JOIN的原因是因为某些订单未使用UserID(仅ClientID)注册。 我已经检查了访问权限,单独访问字段没有问题,当我必须比较LEFT JOIN中的值并指定绝对路径时会出现问题。
你知道什么是错的吗?
答案 0 :(得分:1)
你可以试试这个:
SELECT TOP 200 COALESCE(LTRIM(RTRIM(contact_db.dbo.ContactTable.EmailAdr)),LTRIM(RTRIM(contact_db.dbo.CustomerTable.EmailAdr))) AS EMAIL,
OLAP_invoice.OrdreLinjeID AS ORDERNO
OLAP_invoice.SalgsPris AS PRICE,
OLAP_invoice.UserID AS CONTACTID
FROM OLAP_invoice LEFT JOIN contact_db.dbo.ContactTable ON OLAP_DB.dbo.OLAP_invoice.UserID = contact_db.dbo.ContactTable.UserID, contact_db.dbo.CustomerTable
WHERE contact_db.dbo.CustomerTable.ClientID = OLAP_invoice.ClientID
答案 1 :(得分:1)
您从OLAP_invoice
中选择,但加入OLAP_DB.dbo.OLAP_invoice
。您需要每次都使表格完全相同,或使用别名。
所以:
FROM OLAP_DB.dbo.OLAP_invoice
left join contact_db.dbo.ContactTable
on OLAP_DB.dbo.OLAP_invoice...
OR
FROM ROM OLAP_invoice
LEFT JOIN ontact_db.dbo.ContactTable
ON OLAP_invoice...
或者您也可以使用别名,而不是那样打字。
FROM OLAP_invoice OI
LEFT JOIN ontact_db.dbo.ContactTable CT
ON OI...
答案 2 :(得分:1)
就个人而言,我试图避免在FROM
中有多个表,而没有故意指定联接的类型。
我觉得这样的东西更具可读性和可维护性:
SELECT TOP 200
COALESCE( LTRIM(RTRIM(con.EmailAdr)), LTRIM(RTRIM(cus.EmailAdr)) ) AS EMAIL,
i.OrdreLinjeID AS ORDERNO
i.SalgsPris AS PRICE,
i.UserID AS CONTACTID
FROM OLAP_invoice i
LEFT JOIN contact_db.dbo.CustomerTable cus ON cus.ClientID = i.ClientID
LEFT JOIN contact_db.dbo.ContactTable con ON con.UserID = i.UserID