REGEXP RLIKE

REGEXP(或其同义词,RLIKE)运算符允许基于正则表达式进行模式匹配。

考虑以下 employee 表:

+-------------+-------------+-------------+--------------+----------+
| EMPLOYEE_ID | FIRST_NAME  | LAST_NAME   | PHONE_NUMBER | SALARY   |
+-------------+-------------+-------------+--------------+----------+
|         100 | Steven      | King        | 515.123.4567 | 24000.00 |
|         101 | Neena       | Kochhar     | 515.123.4568 | 17000.00 |
|         102 | Lex         | De Haan     | 515.123.4569 | 17000.00 |
|         103 | Alexander   | Hunold      | 590.423.4567 |  9000.00 |
|         104 | Bruce       | Ernst       | 590.423.4568 |  6000.00 |
|         105 | David       | Austin      | 590.423.4569 |  4800.00 |
|         106 | Valli       | Pataballa   | 590.423.4560 |  4800.00 |
|         107 | Diana       | Lorentz     | 590.423.5567 |  4200.00 |
|         108 | Nancy       | Greenberg   | 515.124.4569 | 12000.00 |
|         109 | Daniel      | Faviet      | 515.124.4169 |  9000.00 |
|         110 | John        | Chen        | 515.124.4269 |  8200.00 |
+-------------+-------------+-------------+--------------+----------+

模式^

选择 FIRST_NAMEN 开头的所有员工。

询问

SELECT * FROM employees WHERE FIRST_NAME REGEXP '^N'
-- Pattern start with----------------------------^

模式$ **

选择 PHONE_NUMBER4569 结尾的所有员工。

询问

SELECT * FROM employees WHERE PHONE_NUMBER REGEXP '4569$'
-- Pattern end with----------------------------------^

不是 REGEXP

选择 FIRST_NAME N 开头的所有员工。

询问

SELECT * FROM employees WHERE FIRST_NAME NOT REGEXP '^N'
-- Pattern does not start with---------------^

正则表达式包含

选择其 LAST_NAME 包含了所有员工,其 FIRST_NAME 包含 a

询问

SELECT * FROM employees WHERE FIRST_NAME REGEXP 'a' AND LAST_NAME REGEXP 'in'
-- No ^ or $, pattern can be anywhere -------------------------------------^

[]之间的任何字符

选择 FIRST_NAMEABC 开头的所有员工。

询问

SELECT * FROM employees WHERE FIRST_NAME REGEXP '^[ABC]'
-------------------------------------------------^^---^

图案或|

选择 FIRST_NAMEABC 开头并以 rei 结尾的所有员工。

询问

SELECT * FROM employees WHERE FIRST_NAME REGEXP '^[ABC]|[rei]$'
-- ----------------------------------------------^^---^^^---^^

计算正则表达式匹配

请考虑以下查询:

SELECT FIRST_NAME, FIRST_NAME REGEXP '^N' as matching FROM employees

FIRST_NAME REGEXP '^N'1 或 *0,*取决于 FIRST_NAME 匹配^N 的事实。

更好地可视化:

SELECT 
FIRST_NAME, 
IF(FIRST_NAME REGEXP '^N', 'matches ^N', 'does not match ^N') as matching 
FROM employees

最后,计算匹配和不匹配行的总数:

SELECT
IF(FIRST_NAME REGEXP '^N', 'matches ^N', 'does not match ^N') as matching,
COUNT(*) 
FROM employees 
GROUP BY matching