SQL Server全文搜索 - 多對多關系

[英]SQL Server full-text search - many-to-many relationship

I'm working on a project with SQL Server 2008 where I believe full-text search is the best way to go. I've been reading up on it as much as I can, and pretty much understand hos to set it up for a single table. However I'm not entirely sure how to set it up with my scenario - imagine the following table structure:

我正在開發一個SQL Server 2008項目,我相信全文搜索是最好的方法。我一直在閱讀它,並且非常了解如何設置單個表格。但是我不完全確定如何使用我的場景進行設置 - 想象下面的表格結構:


- Id
- Title
- Description



- BookId
- AuthorId



- Id
- Name

As you can see, the database holds a table with books, and each book can have none, one or many authors. Each author can also be part of none, one or many books - i.e. the Book and Author tables have a many-to-many relationship, handled with the linking table BookAuthor.

如您所見,數據庫包含一個包含書籍的表格,每本書可以沒有,一個或多個作者。每個作者也可以是無,一本或多本書的一部分 - 即書和作者表具有多對多關系,用鏈接表BookAuthor處理。

What I want to accomplish at this point is a search tool to find matching books based on a search string the user provides. So if the user types in Brown I would want to find all books where either of the following columns contains the word Brown:



In essence, I want a result set of books, including both the book with the title Brown Bear and the books written by author Dan Brown. If there are any suggestions out there as to how I should set this up, I'd really appreciate your input!

本質上,我想要一套結果書,包括標題為Brown Bear的書和作者Dan Brown寫的書。如果有任何建議我應該如何設置,我真的很感激你的意見!

(as a side note, once I have this filtering working, the query result would also need to be sortable and pageable, handled via @SortOrder, @PageIndex and @PageSize passed into a Stored Procedure - but I guess that could be a separate question afterwards!)

(作為旁注,一旦我進行了這個過濾,查詢結果也需要是可排序和可分頁的,通過@SortOrder處理,@ PageIndex和@PageSize傳遞到存儲過程 - 但我想這可能是一個單獨的問題之后!)

1 个解决方案



A CONTAINS predicate can take a list of columns to search as its first argument; however, these columns must be from a single table. You have a couple of options for getting around this limitation. One option is that you can perform two separate searches, one on each table, and then UNION the results together.


select Id, Title from Book where contains([Description], 'brown')
select b.Id, b.Title
    from Book b inner join BookAuthor ba on b.Id = ba.BookId
        inner join Author a on a.Id=ba.AuthorId
    where contains([Name], 'brown')

Another option is to take advantage of the fact that FTS indexes can be created on indexed views. To do this, create an indexed view that contains both the Title field from the Book table and the Name field from the Author table, and then create a FTS index on both of these columns in the view. Then you can write queries against this view as follows:


select BookId, Title from vw_BooksAndAuthors 
where contains(([Description], [Name]), 'brown')



粤ICP备14056181号  © 2014-2020 ITdaan.com