繁体   English   中英

尝试在两个表上进行左联接,但只希望右表中的一个

[英]Trying to do a LEFT JOIN on two tables but want only one from the RIGHT 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 ,在该联接中,我仅联接表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' 

尝试使用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

(但是,该列始终相同,这表示表设计不正确。)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM