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.
I tried left join, and it gave me everything from TABLE 2 (Understandably). I looked at other queries online but got lost.
Can anyone help me with this?
EDIT
Starting query (from OP's comments):
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:
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.
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.