尝试在两个表上执行LEFT JOIN但只想从RIGHT TABLE中选择一个

时间:2015-08-31 13:11:55

标签: sql join left-join

所以我有两张桌子。

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,其中我只加入表2中的一个匹配行。连接将在Receiver列上,每个表中的ID列不同。

我尝试了左连接,它给了我表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' 

4 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

您可以将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' 

答案 2 :(得分:0)

由于您只对每个记录的一列感兴趣,您可以使用子查询:

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

(该列始终相同表示表格设计不良。)

答案 3 :(得分:0)

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