Computer >> Máy Tính >  >> Lập trình >> MySQL

Truy vấn MySQL để tìm kiếm từ chính xác từ chuỗi?

Để tìm kiếm từ chính xác từ chuỗi, hãy sử dụng cú pháp dưới đây -

select *from yourTableName
where
yourColumnName regexp '(^|[[:space:]])yourWord([[:space:]]|$)';

Đầu tiên chúng ta hãy tạo một bảng -

mysql> create table DemoTable
   (
   Title text
   );
Query OK, 0 rows affected (0.23 sec)

Chèn một số bản ghi vào bảng bằng lệnh chèn -

mysql> insert into DemoTable values('This is the Introduction to Java');
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable values('This is the Introduction to MongoDB');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values('This is the Introduction to MySQL');
Query OK, 1 row affected (0.06 sec)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select -

mysql> select *from DemoTable;

Điều này sẽ tạo ra kết quả sau -

+-------------------------------------+
| Title                               |
+-------------------------------------+
| This is the Introduction to Java    |
| This is the Introduction to MongoDB |
| This is the Introduction to MySQL   |
+-------------------------------------+
3 rows in set (0.00 sec)

Sau đây là truy vấn để tìm kiếm từ chính xác từ chuỗi.

mysql> select *from DemoTable
where
Title regexp '(^|[[:space:]])MySQL([[:space:]]|$)';

Điều này sẽ tạo ra kết quả sau -

+-----------------------------------+
| Title                             |
+-----------------------------------+
| This is the Introduction to MySQL |
+-----------------------------------+
1 row in set (0.13 sec)