MySQL : Search keyword in Text Content via Match Against

ระบบฐานข้อมูล MySQL มีฟังก์ชันอำนวยความสะดวกในการค้นหา “คำ (keyword)” จาก “ประโยคยาว (FullText)” ได้โดยเรียกใช้ฟังก์ชัน MATCH() AGAINST() ซึ่งมี Syntax ดังนี้

MATCH(Content) AGAINST(‘Keyword‘)

ตัวอย่าง

สมมติมีตารางที่เก็บข้อมูลที่มีประโยคยาวๆหลายๆบรรทัด และเราต้องการค้นหาว่ามีบรรทัดไหนที่มีข้อความที่ต้องการ ทำได้ดังนี้

drop table if exists tst_content ;
create table tst_content
( `id` INT(11) NOT NULL auto_increment,
`body` text not null,
FULLTEXT (body),
primary key (`id`)
)ENGINE=MyISAM;

insert into tst_content (body) values
(‘DBMS stands for DataBase …’),
(‘After you went through a …’),
(‘In this tutorial we will show …’),
(‘1. Never run mysqld as root. 2. …’),
(‘In the following database comparison …’),
(‘When configured properly, MySQL …’);

จากตัวอย่างตารางที่เก็บประโยคข้อความ สมมติว่าต้องการค้นหาบรรทัดที่มีคำว่า “database” สามารถเรียก sql ได้ดังนี้

SELECT * FROM tst_content
WHERE MATCH (body) AGAINST (‘database’);

ซึ่งจะได้ผลลัพธ์ดังนี้

id body
5 In the following database comparison …
1 DBMS stands for DataBase …

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *