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

Chọn truy vấn có biểu thức chính quy trong MySQL

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

mysql> create table DemoTable1573
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentCode varchar(20)
   -> );
Query OK, 0 rows affected (0.63 sec)

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

mysql> insert into DemoTable1573(StudentCode) values('STU_774');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1573(StudentCode) values('909_Sam');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1573(StudentCode) values('3_Carol_455');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1573(StudentCode) values('David_903');
Query OK, 1 row affected (0.14 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 DemoTable1573;

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

+-----------+-------------+
| StudentId | StudentCode |
+-----------+-------------+
|         1 | STU_774     |
|         2 | 909_Sam     |
|         3 | 3_Carol_455 |
|         4 | David_903   |
+-----------+-------------+
4 rows in set (0.00 sec)

Đây là truy vấn để triển khai truy vấn chọn với biểu thức chính quy -

mysql> select * from DemoTable1573 where StudentCode regexp '\land[0-9]';

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

+-----------+-------------+
| StudentId | StudentCode |
+-----------+-------------+
|         2 | 909_Sam     |
|         3 | 3_Carol_455 |
+-----------+-------------+
2 rows in set (0.14 sec)