2016-08-22 303 views
2

我有2個表,即;SQL查詢 - 兩個表之間的數據匹配

TableA中有大約1000萬行,
TableB中大約50萬行

TableA (10million rows) 
Url 
------------------------------------------- 
http://www.example.com/data/tuesday-morning 
http://www.example.com/data/wednesday-evening 



TableB (500k rows) 
Keyword   Value 
---------  ---------- 
Sunday    0 
Monday    0 
Tuesday    0 
Wednesday   0 

我想搜索在TableATableB所有關鍵字,並找到匹配,其中一個匹配更新有其Value1

我使用MERGE,但問題是至少需要10個小時才能進行搜索。

我會作出這樣的搜索每天,由於這些關鍵字在TableB

MERGE INTO TableB As TB 
USING (Select Url From TableA) As TA 
ON TA.Url LIKE 'http://www.example.com/data/'+TB.Keyword+'-%' 
WHEN MATCHED THEN 
UPDATE SET TB.Value=1; 

每日更新什麼將是最好的SQL查詢,使這兩個表之間最快的查找?

非常感謝

+1

擺脫'(選擇URL從表A)'這是肯定減慢您的查詢,只使用'TableA' – gofr1

+0

隨着該行數量的唯一方法 - 使用全文索引。也就是 - 採用以下由tinka(http://stackoverflow.com/a/39080778/2746150)提出的方法,但是您必須用特定於全文的語言結構來替換'like'%'+ t2.keyword +'%''文本索引更快。 –

回答

1

如果我理解您的問與答可能是該解決方案將幫助您,您可以通過ID或東西塗抹一些WHERE子句,以便您可以糾正什麼事情與你的記錄先用少量的數據應用,那麼你可以申請您的所有數據。

-- declare table1 
declare @table1 table 
(url varchar(max)) 

insert into @table1 
values 
('http://www.example.com/data/tuesday-morning'), 
('http://www.example.com/data/tuesday-morning'), 
('http://www.example.com/data/noday-morning') 


-- declare table2 
declare @table2 table 
(keyword varchar(33), val int) 

insert into @table2 
values 
('monday',0), 
('tuesday',0) 

-- select 
select * from 
@table1 t1 join 
@table2 t2 on t1.url like '%'+t2.keyword+'%' 

-- update 
update 
@table2 
set val =1 
from 
@table1 t1 join 
@table2 t2 on t1.url like '%'+t2.keyword+'%' 

    -- select again 
select * from 
@table1 t1 join 
@table2 t2 on t1.url like '%'+t2.keyword+'%'