使用跨多个表的全文搜索来搜索记录

时间:2012-07-27 05:52:22

标签: sql-server full-text-search

SELECT A.a, B.b, akt.[Rank] + bkt.[Rank] /2  AS [Rank]
FROM B b
INNER JOIN Publication a ON a.Id = b.Id
INNER JOIN FREETEXTTABLE(A, a, 'search text') akt ON a.Id = akt.[Key]
INNER JOIN FREETEXTTABLE(B, b, 'search text') bkt ON b.Id = bkt.[Key] 
ORDER BY [Rank] DESC

UNION
SELECT A.a, null as B.b, akt.[Rank] as [Rank]
FROM A a
INNER JOIN FREETEXTTABLE(A, a, 'search text') akt ON a.Id = akt.[Key]

UNION
SELECT null as A.a, B.b, bkt.[Rank] as [Rank]
FROM B b
INNER JOIN FREETEXTTABLE(A, a, 'search text') akt ON a.Id = akt.[Key]

上述查询用于在两个表中搜索记录(使用排名)。

第一个查询:只显示那些记录,其中搜索文本位于两个表的两列中。

第二次查询:只有那些searchtext仅在表A的第a列中的记录

第三次查询:只有那些searchtext仅在表B的b列中的记录

我的问题是:如果我必须搜索4或5个表,UNIONS的数量会像疯了一样增加。它也会太复杂和缓慢。

那么,还有其他方法可以减少这些UNIONS吗? 我试过了Views,但它们不能全文索引。

2 个答案:

答案 0 :(得分:0)

只需使用完整联接

SELECT A.a, B.b, "Use case for calculating rank"
    FROM B b
    FULL JOIN A a ON b.Id = a.Id
WHERE
    a.[columnname] = 'search text' OR
    b.[columnname] = 'search text' 

检查http://codesnout.com/SQLSample/SQL-FULL-JOIN.php

答案 1 :(得分:0)

SELECT b.FK_Publication_ID, b.PageNumber as PageNumber, b.SearchText as SearchText, a.Title as Title , 
TitleSearch.[Rank] + PubSearch.[Rank] * 10000
  AS [Rank]
FROM PublicationSearch 
INNER JOIN Publication a ON b.FK_Publication_Id = a.Id
INNER JOIN FREETEXTTABLE(PublicationSearch, SearchText, "searchtext") PubSearch ON b.Id = PubSearch.[Key] 
INNER JOIN FREETEXTTABLE(Publication, Title, "searchtext") TitleSearch ON a.Id = TitleSearch.[Key] 
WHERE b.FK_ContentType_Id IN (SELECT * FROM UF_CSVToTable(@Options))

UNION 


SELECT  a.Id, null as PageNumber, null as Searchtext, a.Title as Title, TitleSearch.[Rank] * 100  AS [Rank]
FROM Publication a
INNER JOIN FREETEXTTABLE(Publication,Title, "searchtext") TitleSearch ON a.Id = TitleSearch.[Key]


UNION

SELECT b.FK_Publication_ID, b.PageNumber as PageNumber, b.SearchText as SearchText, null as Title, 
PubSearch.[Rank] 
  AS [Rank] 
FROM PublicationSearch b
INNER JOIN FREETEXTTABLE(PublicationSearch, SearchText, "searchtext") PubSearch ON b.Id = PubSearch.[Key] 

ORDER BY [Rank] DESC

以上是使用UNION

以下是您的建议

SELECT b.FK_Publication_ID,b.PageNumber as PageNumber,b.SearchText as SearchText,a.Title as Title as ContentType,

TitleSearch.[Rank] * 100  (Ranking, dont know how to do it here)
  AS [Rank]
FROM PublicationSearch b
INNER JOIN Publication a ON b.FK_Publication_Id = a.Id
JOIN FREETEXTTABLE(PublicationSearch, SearchText, "searchtext")PubSearch ON b.Id = PubSearch.[Key] 
FULL JOIN FREETEXTTABLE(Publication, Title, "searchtext")TitleSearch ON a.Id = TitleSearch.[Key] 

order by [RANK] desc

Heres,确切的剧本。使用完全连接,我从只有PublicationSearch表的BOTH表和记录中获取记录但不仅来自Publication表

此外,在两个表中找到的记录应排名更高,然后仅来自Publication表的记录和来自PublicationSerach表的THEN记录

谢谢..