使用 MySQL 中的 MATCH 和 AGAINST 選擇包含特定列中某個字串的行


首先建立一張表 −

mysql> create table DemoTable1833
     (
     Name varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

修改表 −

Mysql> alter table DemoTable1833 ADD FULLTEXT(Name);
Query OK, 0 rows affected, 1 warning (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 1

在表中插入一些記錄,使用 insert 命令 −

mysql> insert into DemoTable1833 values('John Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1833 values('Adam Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1833 values('Chris Brown');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1833 values('John Smith');
Query OK, 1 row affected (0.00 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select * from DemoTable1833;

這會產生以下輸出 −

+-------------+
| Name        |
+-------------+
| John Doe    |
| Adam Smith  |
| Chris Brown |
| John Smith  |
+-------------+
4 rows in set (0.00 sec)

以下是查詢包含特定列中字串的行

mysql> select * from DemoTable1833 where MATCH(Name) AGAINST('+John Smith+') ;

這會產生以下輸出 −

+------------+
| Name       |
+------------+
| John Smith |
| John Doe   |
| Adam Smith |
+------------+
3 rows in set (0.00 sec)

更新於: 24-12-2019

206 次瀏覽

開啟 職業生涯

透過完成課程獲得認證

開始
廣告