全文MySQL搜索 - 返回片段

时间:2012-09-04 18:36:10

标签: mysql full-text-search

我有一个MySQL表,其中包含书籍章节。

Table: book_chapter
--------------------------
| id | book_id | content |
--------------------------

我目前可以使用全文搜索来搜索内容,如下所示:

SELECT * FROM book_chapter WHERE book_chapter.book_id="2" AND
MATCH (book_chapter.content) AGAINST ("unicorn hair" IN BOOLEAN MODE)

但是,我想知道是否可以搜索内容并以30个字符的片段返回结果,这样用户就可以感受到要点。例如,如果我搜索" unicorn hair",我会得到这样的结果:

-------------------------------------------------
| id | book_id | content                        |
-------------------------------------------------
| 15 |    2    | it isn't unicorn hair. You kno |
 -------------------------------------------------
| 15 |    2    | chup and unicorn hair in soup  |
 -------------------------------------------------
| 27 |    2    | , should unicorn hair be used  |
 -------------------------------------------------
| 31 |    2    | eware of unicorn hair for bal  |

请注意,同一记录有两个结果。那可能吗?

2 个答案:

答案 0 :(得分:2)

Mike Bryant对查询的改进

如果匹配位于字段的开头,则SUBSTRING将从结尾开始。

我刚刚添加了一个IF语句来修复它

SELECT 
    id, 
    book_id, 
    SUBSTRING(
        content, 
        IF(LOCATE("unicorn hair", content) > 10, LOCATE("unicorn hair", content) - 10, 1),
        10 + LENGTH("unicorn hair") + 10
    ) 
FROM 
    book_chapter 
WHERE book_chapter.book_id="2" 
AND MATCH (book_chapter.content) AGAINST ("unicorn hair" IN BOOLEAN MODE)

答案 1 :(得分:1)

尝试这样的方法来创建搜索短语的第一个匹配的片段加上前面的10个字符和后面的10个字符(这不是30个字符的长度,但可能是更好的解决方案,具体取决于长度搜索词组,即如果您的搜索词组> 30个字符,该怎么办?这并不能解决您希望在结果集中显示同一记录的多个结果的愿望。对于类似的东西,我几乎认为你最好的服务器创建一个存储过程来完成你想要的工作。

SELECT id, book_id, SUBSTRING(content, LOCATE("unicorn hair", content) - 10, 10 + LENGTH("unicorn hair") + 10) FROM book_chapter WHERE book_chapter.book_id="2" AND
MATCH (book_chapter.content) AGAINST ("unicorn hair" IN BOOLEAN MODE)

显然你会替换"独角兽的头发"无论您的搜索短语位于其所有位置。

相关问题