在上下文中提取搜索字符串

[英]Extract a search string in context


I'm trying to do a MySQL query where I extract the search string in context. So if the search is "mysql" I'd like to return something like this from the 'body' column

我正在嘗試進行MySQL查詢,我在上下文中提取搜索字符串。因此,如果搜索是“mysql”,我想從“body”列返回這樣的內容

"It only takes minutes from downloading the MySQL Installer to having a ready to use"

“從下載MySQL安裝程序到准備使用只需幾分鍾”

This is what I've got now but it doesn't work because it just grabs the first 20 characters from the body field. While I'd like it to grab 20 chars in front of and behind the searched term so that the user can see what there term looks like in context:

這就是我現在所擁有的,但它不起作用,因為它只是從身體字段中抓取前20個字符。雖然我希望在搜索詞的前面和后面抓取20個字符,以便用戶可以在上下文中查看該術語的含義:

SELECT id, title, substring(body, 0, 20)  FROM content WHERE body LIKE '%mysql%' OR title LIKE '%mysql%';

Thanks

謝謝

2 个解决方案

#1


2  

Here's the SQL you need:

這是您需要的SQL:

SELECT
    id,
    title,
    substring(body,  
        case
             when locate('mysql', lower(body)) <= 20 then 1
             else locate('mysql', lower(body)) - 20
        end,
        case
            when locate('mysql', lower(body)) + 20 > length(body) then length(body)
            else locate('mysql', lower(body)) + 20
        end)
FROM content
WHERE lower(body) LIKE '%mysql%'
    OR title LIKE '%mysql%'
limit 8;

FYI: Tested and works.

僅供參考:經過測試和工作。

#2


1  

You could just pull the whole body value out and just extract the string in your code. If you're using php, you could do something like this, given you've already queried the body string and stored it in a var $body

您可以將整個身體值拉出來,只需在代碼中提取字符串即可。如果你正在使用php,你可以做這樣的事情,因為你已經查詢了正文字符串並將其存儲在var $ body中

$index = strpos($body, $searchStr);
$context = substr($body, $index-20, strlen($searchStr)+40);

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/06/03/712b3bbdc56d274d862dbcff6b5fbcc4.html



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