尝试在两个表上执行 LEFT JOIN 但只需要一个来自 RIGHT TABLE

Trying to do a LEFT JOIN on two tables but want only one from the RIGHT TABLE

所以我有两个 table。

Table 1

ID    Receiver  Some  Columns

1  43523  Ba  Baa

2  82822  Boo  Boo

Table 2

ID    Receiver  Some2  Columns2

1 - 43523  OO  JJ

2 - 43523  OO  NULL

3 - 43523  OO  YABA DABA

所以,现在我想做一个 left join,其中我只加入来自 table 的匹配行之一 2. 加入将在 Receiver 列上,每个 ID 列table不一样。

我尝试了 left join,它给了我 TABLE 2(可以理解)中的所有内容。我在网上查看了其他查询,但迷路了。

谁能帮我解决这个问题?

编辑

开始查询(来自 OP 的评论):

SELECT Table1.[ID],
       Table1.[Receiver],
       Table2.[Some2],
       Table1.[Some],
       Table1.[Columns]
  FROM Table1
  LEFT JOIN Table2
    ON Table1.Receiver = Table2.ReceiverID
 WHERE Some = 544
   AND Columns = 'xyz' 

尝试使用 group by 使 Receiver 列唯一:

SELECT t1.*, t2.*
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 ON t1.Receiver = t2.Receiver
GROUP BY t2.Receiver

您可以将您的 left join 更改为正常的 join,因为您总是期待匹配。

并且要将匹配限制为单行,您可以使用 row_number over (),其中 order by 子句没有意义,因为您不关心匹配到哪一行。

SELECT Table1.[ID],
       Table1.[Receiver],
       t2.[Some2],
       Table1.[Some],
       Table1.[Columns]
  FROM Table1
  JOIN (SELECT *,
               row_number() over (partition by ReceiverID order by ReceiverID) as rn
          FROM Table2) t2
    ON Table1.Receiver = t2.ReceiverID
   AND t2.rn = 1
 WHERE Some = 544
   AND Columns = 'xyz' 

由于您只对每条记录都相同的列感兴趣,因此可以使用子查询:

select t1.*, (select max(some2) from table2 t2 where t2.receiver = t1.receiver)
from table1 t1

(该列始终相同表明 table 设计不好。)

select *
from
    T1 as t1 inner join
    (select Receiver, min(Some2) as Some2 from T2 group by Receiver) as t2
        on t2.Receiver = t1.Receiver