簡體   English   中英

加入兩個表,但在第一次匹配后停止並保留左表中的所有行

[英]Join two tables but stop after first match and keep all rows from Left table

預先感謝您花時間考慮我的問題。 我有以下兩個表:

pcid表:

PCID
pcidtest1
pcidtest1
示例 pcid2
foocid3
barexample4

匹配表:

渠道 匹配字符串
測試通道1 pcid測試
測試通道2 pcid
測試通道3 酒吧

我想在PCID包含Match String作為 substring 的情況下合並表。當 PCID 僅匹配一行時,這很容易做到,因為這將是一個簡單的連接。 但是,當 PCID 包含來自多行的Match String時,我只希望它從第一個“匹配”開始加入。 因此,這兩個表的結果理想情況下如下所示:

理想結果表:

PCID 渠道
pcidtest1 測試通道1
pcidtest1 測試通道1
示例 pcid2 測試通道2
foocid3 測試通道2
barexample4 測試通道3

如果我執行這樣的查詢,我會為每個值為“pcidtest1”的 PCID 行獲取多行,因為“pcidtest1”同時包含“pcidtest”和“pcid”:

-- Assume REGEXP_CONTAINS is a built in method that will return a
-- boolean signifying whether or not the second parameter is
-- a substring of the first.
SELECT pcidTable.pcid, matchTable.channel
FROM pcidTable
LEFT JOIN matchTable 
  ON REGEXP_CONTAINS(pcidTable.pcid, matchTable.match_string)

上面的腳本會生成這個表,這不是我想要的,因為它包含每個具有多個匹配項的 PCID 的多行:

PCID 渠道
pcidtest1 測試通道1
pcidtest1 測試通道2
pcidtest1 測試通道1
pcidtest1 測試通道2
示例 pcid2 測試通道2
foocid3 測試通道2
barexample4 測試通道3

相反,我想要一個表(參見上面的“IDEAL RESULT TABLE”),它只包含 pcidTable 中每一行的一行,它在pcidTable中看到的第一個匹配matchTable 需要注意兩點:

  • 我們可以假設matchTable是按照匹配字符串的長度降序排列的。
  • 此示例將導致重復行 (pcidtest1 <--> TestCh1),但我們也希望保留它們。

有沒有人知道如何處理這個問題?

我嘗試編寫一個 function,我將PCID字符串傳遞給它以針對matchTable進行查詢,但問題的約束不允許我在 function 中使用子查詢,並且必須在連接子句中完成。

這是非常低效的,但它會起作用 -

WITH pcidNumbered AS (
  SELECT pcid, ROW_NUMBER() OVER() row_num
  FROM pcidTable
)
SELECT pcid, channel
FROM (
  SELECT *, COUNT(*) OVER(PARTITION BY row_num ORDER BY LENGTH(match_string) DESC) c
  FROM pcidNumbered p
  LEFT JOIN matchTable m
    ON p.pcid LIKE CONCAT('%', m.match_string, '%')
) t
WHERE c = 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM