位置:首頁 > 數據庫 > PostgreSQL教學 > PostgreSQL LIKE語句

PostgreSQL LIKE語句

PostgreSQL的LIKE操作符是用來反對使用通配符的模式匹配的文本值。如果搜索表達式可以匹配的模式表達式,LIKE運算將返回true,也就是1。

有兩個通配符與LIKE運算符一起使用:

  • 百分號 (%)

  • 下劃線 (_)

百分號表示零個,一個或多個數字或字符。下劃線代表一個單一的數字或字符。這些符號可以被組合使用。

那麼,如果這兩個標誌結合LIKE子句中不使用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子句以'%'和'_'運算符具有不同的部分:

Statement Description
WHERE SALARY::text LIKE '200%' Finds any values that start with 200
WHERE SALARY::text LIKE '%200%' Finds any values that have 200 in any position
WHERE SALARY::text LIKE '_00%' Finds any values that have 00 in the second and third positions
WHERE SALARY::text LIKE '2_%_%' Finds any values that start with 2 and are at least 3 characters in length
WHERE SALARY::text LIKE '%2' Finds any values that end with 2
WHERE SALARY::text LIKE '_2%3' Finds any values that have a 2 in the second position and end with a 3
WHERE SALARY::text LIKE '2___3' Finds any values in a five-digit number that start with 2 and end with 3
Postgres的LIKE隻字符串比較。因此需要顯式地將字符串作為整數列在上麵的例子中。

讓我們舉一個現實的例子,考慮表公司有如下記錄:

# select * from COMPANY;
 id | name  | age | address   | salary
----+-------+-----+-----------+--------
  1 | Paul  |  32 | California|  20000
  2 | Allen |  25 | Texas     |  15000
  3 | Teddy |  23 | Norway    |  20000
  4 | Mark  |  25 | Rich-Mond |  65000
  5 | David |  27 | Texas     |  85000
  6 | Kim   |  22 | South-Hall|  45000
  7 | James |  24 | Houston   |  10000
(7 rows)

以下是一個例子,它會從公司表顯示年齡以2開始所有記錄:

testdb=# SELECT * FROM COMPANY WHERE AGE::text LIKE '2%';

這將產生以下結果:

 id | name  | age | address     | salary
----+-------+-----+-------------+--------
  2 | Allen |  25 | Texas       |  15000
  3 | Teddy |  23 | Norway      |  20000
  4 | Mark  |  25 | Rich-Mond   |  65000
  5 | David |  27 | Texas       |  85000
  6 | Kim   |  22 | South-Hall  |  45000
  7 | James |  24 | Houston     |  10000
  8 | Paul  |  24 | Houston     |  20000
(7 rows)

以下是一個例子,它會顯示所有記錄從公司表的地址將有一個連字符( - ),裡麵的文字:

testdb=# SELECT * FROM COMPANY WHERE ADDRESS  LIKE '%-%';

這將產生以下結果:

 id | name | age |                      address              | salary
----+------+-----+-------------------------------------------+--------
  4 | Mark |  25 | Rich-Mond                                 |  65000
  6 | Kim  |  22 | South-Hall                                |  45000
(2 rows)