[英]Trying to do a LEFT JOIN on two tables but want only one from the RIGHT TABLE
So I have two tables. 所以我有两个桌子。
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
So, Now I want to do a left join
where in I join only one of the matching rows from table 2. THe join will be on Receiver column, and the ID column in each table is different. 因此,现在我想做一个left join
,在该联接中,我仅联接表2中的匹配行之一。联接将在Receiver列上,并且每个表中的ID列都不同。
I tried left join, and it gave me everything from TABLE 2 (Understandably). 我尝试了左联接,它给了我表2中的所有内容(理解)。 I looked at other queries online but got lost. 我在网上查看了其他查询,但迷路了。
Can anyone help me with this? 谁能帮我这个?
EDIT 编辑
Starting query (from OP's comments): 开始查询(根据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'
Try using a group by
to make the Receiver
column unique: 尝试使用group by
以使“ Receiver
列唯一:
SELECT t1.*, t2.*
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 ON t1.Receiver = t2.Receiver
GROUP BY t2.Receiver
You can change your left join
to a normal join
, since you are always expecting a match. 您可以将left join
更改为普通join
,因为您一直期待匹配。
And to limit the matches to a single row, you can use row_number over ()
, where the order by
clause is meaningless, since you don't care which row you are matching to. 为了将匹配项限制为单行,可以使用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'
As you are only interested in one column which is the same for every record, you can use a subquery: 因为您只对每条记录都相同的一列感兴趣,所以可以使用子查询:
select t1.*, (select max(some2) from table2 t2 where t2.receiver = t1.receiver)
from table1 t1
(That column being always the same indicates a bad table design however.) (但是,该列始终相同,这表示表设计不正确。)
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.