search
HomeDatabaseMysql Tutorialmysql全文搜索 sql命令的写法

首先,大家先去下载一份dvbbs.php beta1的代码,解压后先抛开php代码,找出你的mysql手册,如果没有手册那么就直接看下面的实例操作吧!

mysql全文搜索,sql的写法:
MATCH (col1,col2,…) AGAINST (expr [IN BOOLEAN MODE | WITH QUERY EXPANSION])
比如:
SELECT * FROM articles WHERE MATCH (title,body) AGAINST ('database');
MATCH()函数对于一个字符串执行资料库内的自然语言搜索。一个资料库就是1套1个或2个包含在FULLTEXT内的列。搜索字符串作为对 AGAINST()的参数而被给定。对于表中的每一行, MATCH() 返回一个相关值,即, 搜索字符串和 MATCH()表中指定列中该行文字之间的一个相似性度量。
下面的例子则更加复杂。询问返回相关值,同时对行按照相关性渐弱的顺序进行排序。为实现这个结果,你应该两次指定 MATCH(): 一次在 SELECT 列表中而另一次在 WHERE子句中。这不会引起额外的内务操作,原因是MySQL 优化程序注意到两个MATCH()调用是相同的,从而只会激活一次全文搜索代码。
代码如下:
mysql> SELECT id, body, MATCH
(title,body) AGAINST
-> ('Security implications of
running MySQL as root') AS score
-> FROM articles WHERE MATCH
(title,body) AGAINST
-> ('Security implications of
running MySQL as root');

所以,到这里你应该会mysql 英文全文搜索了.
请注意一个问题.
一些词在全文搜索中会被忽略:
* 任何过于短的词都会被忽略。 全文搜索所能找到的词的默认最小长度为 4个字符。
* 停止字中的词会被忽略。
mysql还自带查询扩展功能.这里不做过多讨论.
下面进行php中文全文搜索的分析
曾经有一个版本的mysql支持中文全文搜索(海量 mysql chinese+,说是GPL但是最终没有开源)
中文全文搜索的关键是在分词上.mysql本身不支持cjk的分词(cjk:chinese,japanese,korean),
所以
!!!!****如何用php模拟分词是mysql全文索引的关键****!!!!
中文分词是语言分词中最困难的.现在也没有人能够彻底完美的解决(虽然这些搜索引擎做的都还不错.)
代码如下:
//fcicq:下面给大家看看这里php的分词是怎么做的.
function &DV_ChineseWordSegment($str,$encodingName='gbk'){
static $objEnc = null;
if( $objEnc === null ){
if( !class_exists('DV_Encoding') ){
require_once ROOT_PATH.'inc/DV_Encoding.class.php';
}
$objEnc =& DV_Encoding::GetEncoding($encodingName);
}
$strLen = $objEnc->StrLength($str);
$returnVal = array();
if( $strLen return $str;
}
$arrStopWords =& DV_GetStopWordList();
//print_r($arrStopWords);
//过滤所有HTML标签
$str = preg_replace('#|#is', ”, $str);
//过滤所有stopword
$str = str_replace($arrStopWords['StrRepl'],' ‘,$str);
$str = preg_replace($arrStopWords['PregRepl'],' ‘,$str);
//echo “$str:{$str}
“;
$arr = explode(' ‘,$str);
//fcicq:好了,这下面的才是php分词关键 *************
foreach( $arr as $tmpStr ){
if ( preg_match(”/^[x00-x7f]+$/i”,$tmpStr) === 1 )
{ //fcicq:全是E文,没关系,mysql可以认识的
$returnVal[] = ‘ ‘.$tmpStr;
} else{ //fcicq:中英混合…
preg_match_all(”/([a-zA-Z]+)/i”, $tmpStr, $matches);
if( !empty($matches) ){ //fcicq:英语部分
foreach( $matches[0] as $matche ){
$returnVal[] = $matche;
}
}
//过滤ASCII字符
$tmpStr = preg_replace(”/([x00-x7f]+)/i”, ”
, $tmpStr); //fcicq:你看,剩下的不就全是中文了?
$strLen = $objEnc->StrLength($tmpStr)-1;
for( $i = 0 ; $i $returnVal[] = $objEnc->SubString($tmpStr,$i,2)
; //fcicq:注意这里的substr,不是手册上的.
//fcicq:你仔细看,所有的词都是分成两个.
//比如”数据库的应用”,会被分成数据 据库 库的 的应 应用…
//全文搜索: 全文 文搜 搜索
//这分词自然是不怎么样的
//但是,搜索的时候同样这么做.
//比如搜索数据库,就相当于搜索了数据 据库.
//这是一种相当传统的全文搜索分词方法.
}
}
}
return $returnVal;
}//end function DV_ChineseWordSegment
//fcicq:这就是传说中的substr.偶相信许多人写出来的php代码都比这个好.
function &SubString(&$str,$start,$length=null){
if( !is_numeric($start) ){
return false;
}
$strLen = strlen($str);
if( $strLen return false;
}
if( $start $mbStrLen = $this->StrLength($str);
} else{
$mbStrLen = $strLen;
}
if( !is_numeric($length) ){
$length = $mbStrLen;
} elseif( $length $length = $mbStrLen + $length - 1;
}
if( $start $start = $mbStrLen + $start;
}
$returnVal = '';
$mbStart = 0;
$mbCount = 0;
for( $i = 0 ; $i if( $mbCount >= $length ){
break;
}
$currOrd = ord($str{$i});
if( $mbStart >= $start ){
$returnVal .= $str{$i};
if( $currOrd > 0×7f ){
$returnVal .= $str{$i+1}.$str{$i+2};
$i += 2;
}
$mbCount++;
} elseif( $currOrd > 0×7f ){
$i += 2;
}
$mbStart++;
}
return $returnVal;
}//end function SubString
//插入全文搜索分词表.一共两个,一个 topic_ft,一个bbs_ft
$arrTopicIndex =& DV_ChineseWordSegment($topic);
if( !empty($arrTopicIndex) && is_array($arrTopicIndex) ){
$topicindex = $db->escape_string(implode(' ‘,$arrTopicIndex));
if( $topicindex !== ” ){
$db->query(”UPD ATE {$dv}topic_ft SET topicindex='
{$topicindex}' WHERE topicid='{$RootID}'”);
} else{
$db->query(”DEL ETE FROM {$dv}topic_ft
WHERE topicid='{$RootID}'”);
}
}
}

这就是所谓的mysql全文搜索分词,mysql不会分词,而php会。就这么简单。
这虽然是一种比较过时的方法,但是非常实用。
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

SQL Commands in MySQL: Practical ExamplesSQL Commands in MySQL: Practical ExamplesApr 14, 2025 am 12:09 AM

SQL commands in MySQL can be divided into categories such as DDL, DML, DQL, DCL, etc., and are used to create, modify, delete databases and tables, insert, update, delete data, and perform complex query operations. 1. Basic usage includes CREATETABLE creation table, INSERTINTO insert data, and SELECT query data. 2. Advanced usage involves JOIN for table joins, subqueries and GROUPBY for data aggregation. 3. Common errors such as syntax errors, data type mismatch and permission problems can be debugged through syntax checking, data type conversion and permission management. 4. Performance optimization suggestions include using indexes, avoiding full table scanning, optimizing JOIN operations and using transactions to ensure data consistency.

How does InnoDB handle ACID compliance?How does InnoDB handle ACID compliance?Apr 14, 2025 am 12:03 AM

InnoDB achieves atomicity through undolog, consistency and isolation through locking mechanism and MVCC, and persistence through redolog. 1) Atomicity: Use undolog to record the original data to ensure that the transaction can be rolled back. 2) Consistency: Ensure the data consistency through row-level locking and MVCC. 3) Isolation: Supports multiple isolation levels, and REPEATABLEREAD is used by default. 4) Persistence: Use redolog to record modifications to ensure that data is saved for a long time.

MySQL's Place: Databases and ProgrammingMySQL's Place: Databases and ProgrammingApr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL: From Small Businesses to Large EnterprisesMySQL: From Small Businesses to Large EnterprisesApr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?Apr 13, 2025 am 12:16 AM

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),