簡體   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