Extract a search string in context

自闭症网瘾萝莉.ら 提交于 2020-01-05 03:32:12

问题


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

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

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:

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

Thanks


回答1:


Here's the SQL you need:

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:


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

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


来源:https://stackoverflow.com/questions/6221821/extract-a-search-string-in-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!