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