查询中来自同一表的两个ID-尝试获取两个ID的名称

时间:2019-05-13 16:12:11

标签: sql ms-access

我有几个要链接在一起的表。一张表(tblBrokeragePurchase)包含有关客户完成的采购订单的信息。该表中有一个BuyerID和SellerID。这两个字段都链接到另一个表(tblContacts)。我想输出买方和卖方的全名,但是Access使我有些悲伤,因为我的SQL语句的多个方面都使用了这些字段。

到目前为止,这就是我自己要做的事情:

SELECT [First Name] & " " & [Last Name] AS BuyerName, 
       [First Name] & " " & [Last Name] AS SellerName 
FROM   (tblBrokeragePurchase 
        LEFT JOIN tblContacts 
               ON ( tblBrokeragePurchase.SellerID = tblContacts.ID ) 
                  AND ( tblBrokeragePurchase.BuyerID = tblContacts.ID )) 
       INNER JOIN qryCityLookup 
               ON tblBrokeragePurchase.ID = qryCityLookup.ID 
WHERE  ( ( [BuyerID] = [ID] ) 
         AND ( [SellerID] = [ID] ) ); 

我非常确定这与WHERE语句有关。买方和卖方将不是同一个人(通常是)。因此,我需要在哪里修复SQL中的JOINWHERE语句?

2 个答案:

答案 0 :(得分:2)

您必须两次加入联系表,并使用别名来区分两者

SELECT Buyer.[First Name] & " " & Buyer.[Last Name] AS BuyerName, 
       Seller.[First Name] & " " & Seller.[Last Name] AS SellerName 
FROM   (tblBrokeragePurchase 
        LEFT JOIN tblContacts as Seller
               ON ( tblBrokeragePurchase.SellerID = tblContacts.ID ) 
        LEFT JOIN tblContacts as Buyer
               ON ( tblBrokeragePurchase.BuyerID = tblContacts.ID ) 
       INNER JOIN qryCityLookup 
               ON tblBrokeragePurchase.ID = qryCityLookup.ID 

现在,如果您要查找单个ID,则WHERE子句可能应该是

WHERE  ( ( [BuyerID] = [ID] ) 
         OR ( [SellerID] = [ID] ) ); 

答案 1 :(得分:1)

由于您的查询将为tblContacts中的每个记录访问tblBrokeragePurchase表中的两个 记录,因此需要引用tblContacts记录两次,以便查询可以同时获得两条单独的记录。

在MS Access中,以下应该是有效的SQL:

select
    b.[First Name] & " " & b.[Last Name] as BuyerName, 
    s.[First Name] & " " & s.[Last Name] as SellerName 
from
    (
        (
            tblBrokeragePurchase p left join tblContacts s on p.SellerID = s.ID
        ) 
        left join tblContacts b on p.BuyerID = b.ID
    )
    inner join qryCityLookup c on p.ID = c.ID 
where
    p.BuyerID  = [YourBuyerID] and 
    p.SellerID = [YourSellerID]

附加的圆括号用作MS Access,要求每对联接的表/查询都由单独的圆括号包围-我将描述一般结构here