mysql单词匹配_mysql喜欢在字符串上匹配完整的单词或单词的开头

bd96500e110b49cbb3cd949968f18be7.png

Given a search string I need to select every record where (in the field the search is performed on) there is at least one word that begins with the given text.

For example:

'John Doe'

Have to be be selected with search strings like:

'joh'

'do'

'JOHN doe'

Have not to be selected with

'ohn'

'oe'

I need (possibly) to avoid full text search.

What I've found to work is

$query = 'SELECT * FROM MYTABLE WHERE SEARCHFIELD LIKE "' . $searchText . '%"'

. 'OR SEARCHFIELD LIKE "% ' . $searchText . '%"'

I'm asking if there is a better way to do that.

(for "better way" I mean better performance or same performance but more elegant)

Also, as the query will be built up with a prepared statement, how should I unescape LIKE metacharacters in the search string?

解决方案

As already stated in the question the query

$query = 'SELECT * FROM MYTABLE WHERE SEARCHFIELD LIKE "' . $searchText . '%"'

. 'OR SEARCHFIELD LIKE "% ' . $searchText . '%"'

works for matching records where the SEARCHFIELD contains a word that begins with (or is equal to) $searchText

Regarding performance I've made a test on my development machine MBP 2,2 GHz i7 quad core:

Searching for a word on 4.000 records takes around 40 milliseconds.

Records are normally indexed (no fulltext).

I have few thousands records and the query doesn't run very often so for me is good.

The solution may not be suitable for other contexts.

To build a prepared statement with the above query I used the technique described here:

The resulting code is as follows:

function like($s, $e)

{

return str_replace(array($e, '_', '%'), array($e . $e, $e . '_', $e . '%'), $s);

}

/* ... */

/* create a prepared statement */

$stmt = $mysqli->prepare(

'SELECT * FROM MYTABLE WHERE SEARCHFIELD LIKE ? ESCAPE "=" OR SEARCHFIELD LIKE ? ESCAPE "="'

);

if( $stmt )

{

/* escape the text */

$escSearchText = like( $searchText, "=" );

/* 'like' parameters */

$like1 = $escSearchText . "%";

$like2 = "%" . $escSearchText . "%";

/* bind parameters for markers */

$stmt->bind_param( "ss", $like1, $like2 );

/* ... */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值