SQLite LIKE 子句
SQLite的LIKE操作符是用來反對使用通配符的模式匹配的文本值。如果搜索表達式可以匹配的圖案表達,LIKE運算將返回true,也就是1。有兩個通配符與LIKE運算符一起使用:
-
百分號 (%)
-
下劃線 (_)
百分號表示零個,一個或多個數字或字符。下劃線代表一個單一的數字或字符。這些符號可以被組合使用。
語法
%和_的基本語法如下:
SELECT FROM table_name WHERE column LIKE 'XXXX%' or SELECT FROM table_name WHERE column LIKE '%XXXX%' or SELECT FROM table_name WHERE column LIKE 'XXXX_' or SELECT FROM table_name WHERE column LIKE '_XXXX' or SELECT FROM table_name WHERE column LIKE '_XXXX_'
可以結合的條件下使用AND或OR運算的N多。XXXX在這裡可以是任何數字或字符串值。
例子:
下麵一些例子顯示LIKE子句以'%'和'_'運算符具有不同的部分:
語句 | 描述 |
---|---|
WHERE SALARY LIKE '200%' | Finds any values that start with 200 |
WHERE SALARY LIKE '%200%' | Finds any values that have 200 in any position |
WHERE SALARY LIKE '_00%' | Finds any values that have 00 in the second and third positions |
WHERE SALARY LIKE '2_%_%' | Finds any values that start with 2 and are at least 3 characters in length |
WHERE SALARY LIKE '%2' | Finds any values that end with 2 |
WHERE SALARY LIKE '_2%3' | Finds any values that have a 2 in the second position and end with a 3 |
WHERE SALARY LIKE '2___3' | Finds any values in a five-digit number that start with 2 and end with 3 |
讓我們舉一個實際的例子,考慮COMPANY表有以下記錄:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0
以下是一個例子,它會從公司表顯示年齡以2開頭 的所有記錄:
sqlite> SELECT * FROM COMPANY WHERE AGE LIKE '2%';
這將產生以下結果:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0
以下是一個例子,它會顯示所有記錄從公司表的地址將有一個連字符( - ),裡麵的文字:
sqlite> SELECT * FROM COMPANY WHERE ADDRESS LIKE '%-%';
這將產生以下結果:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 Mark 25 Rich-Mond 65000.0 6 Kim 22 South-Hall 45000.0