SQL Server基本连接

时间:2016-11-25 23:04:15

标签: sql sql-server join

我有两张桌子:

  • 货币1(有172行)
  • 货币2(有278行)

我只想要一个返回172行的连接但是:

SELECT 
    Currencies1.*, Currencies2.*
FROM 
    Currencies1 
INNER JOIN
    Currencies2 ON Currencies1.AlphabeticCode = Currencies2.CurrencyCode;     

返回258行

SELECT Currencies1.*, Currencies2.*
FROM Currencies1 
LEFT JOIN Currencies2 ON Currencies1.AlphabeticCode = Currencies2.CurrencyCode;     

返回268行

SELECT Currencies1.*, Currencies2.*
FROM Currencies1 
LEFT JOIN Currencies2 ON Currencies1.AlphabeticCode = Currencies2.CurrencyCode;     

返回278行

我不知道为什么会这样。

1 个答案:

答案 0 :(得分:0)

这两个表中有重复项。你可以做这样的事情:

SELECT c1.*, c2.*
FROM Currencies1 c1 OUTER APPLY
     (SELECT TOP 1 c2.*
      FROM Currencies2 c2
      WHERE c1.AlphabeticCode = c2.CurrencyCode
     ) c2 ;

这将从第二个表中为结果集选择任意匹配。但是,您可能最好找出两个表中实际上重复的货币代码。