2

嗨,我有一个 SQL 表,它有两个表,它们在一个单独的表中引用相同的外键两次......就像

销售表

idSales idClient1 idClient2
1       1         2

客户表

idClient ClientName
1        Bob
2        Mick

我想将 SALES 表加入 CLIENT 表并返回数据如下:

idSales idClientClientName1 idClientClientName2
1       Bob                 Mick

任何人都可以为此提供 SQL 帮助吗?我在加入时遇到不明确的列名错误。

谢谢

4

3 回答 3

8

您基本上需要在 tableClient上连接 tableSales两次,因为 table 上有两列Sales依赖于 table Client

SELECT  a.idSales,
        b.ClientName ClientName1,
        c.ClientName ClientName2
FROM    Sales a
        INNER JOIN Client b
            ON a.idClient1 = b.idClient
        INNER JOIN Client c
            ON a.idClient2 = c.idClient

要进一步了解有关联接的更多信息,请访问以下链接:

但是,当其中一列或两列都可以为时,INNER JOIN不会为您提供所有记录,Sales因为它只会选择在另一张表上至少有一个匹配项的位置。而是使用LEFT JOIN.

于 2013-05-20T13:43:36.747 回答
1

I might add that in cases like this, I use table aliases that hint at what entity you are linking to in the joined table. If for example, the foreign keys were to an address table, and you had a work address, and a Home address, I would use tables aliases of h and w for the two joins. In your case, i.e.,

Selext s.idSales,
    c1.ClientName ClientName1,
    c2.ClientName ClientName2
From Sales s
    Join Client c1
        On c1.idClient = s.idClient1
    Join Client c2
        On c2.idClient = s.idClient2
于 2013-05-20T13:50:01.897 回答
0

对于那些将来可能会看到这个问题的 SQL 初学者来说,添加 AS 单词会很有帮助,这样会更清楚:

SELECT
Sale.idSales,
c1.ClientName AS ClientName1,
c2.ClientName AS ClientName2
FROM
Sales AS Sale
INNER JOIN Client AS c1 ON Sale.idClient1 = c1.idClient
INNER JOIN Client AS c2 ON Sale.idClient2 = c2.idClient
于 2013-05-20T14:47:56.103 回答