摘要:在本教程中,您將學習如何使用 SQL POSITION 函式來查詢子字串在字串中首次出現的位置。
SQL POSITION 函式簡介 #
在 SQL 中,POSITION 函式返回一個整數,表示子字串在字串中首次出現的位置。
以下是 POSITION 函式的語法:
POSITION(substring IN string)Code language: SQL (Structured Query Language) (sql)POSITION 接受兩個引數:
substring:您要查詢的字元序列。string:您要在其中搜索子字串的字串。
POSITION 函式返回一個整數,表示子字串首次出現的位置。該位置是一個基於 1 的索引,意味著字串中的第一個字元位置為 1,依此類推。
如果子字串不存在,POSITION 函式將返回 0。
基本的 SQL POSITION 示例 #
以下示例使用 POSITION 示例來查詢字串 "SQL" 在字串 "SQL will, SQL will rock you!" 中首次出現的位置。
SELECT
POSITION('SQL' IN 'SQL will, SQL will rock you!') AS sql_position;Code language: PHP (php)輸出
sql_position
--------------
1以下示例返回零,因為輸入字串中不包含子字串 “We”。
SELECT
POSITION('We' IN 'SQL will, SQL will rock you!') AS result;Code language: PHP (php)輸出
result
--------
0在員工姓名中查詢子字串的位置 #
我們將使用 HR 示例資料庫中的 employees 表來演示 POSITION 函式。

以下查詢使用 POSITION 函式來查詢 first_name 列中包含字母 A 的員工及其位置。
SELECT
first_name,
POSITION('A' IN first_name) AS position_of_a
FROM
employees
WHERE
POSITION('A' IN first_name) > 0;Code language: SQL (Structured Query Language) (sql)輸出
first_name | position_of_a
------------+---------------
Alexander | 1
Alexander | 1
Adam | 1
...Code language: SQL (Structured Query Language) (sql)根據子字串位置篩選行 #
以下語句使用 POSITION 函式來查詢電子郵件地址以字母 J 開頭的員工。
SELECT
email
FROM
employees
WHERE
POSITION('j' IN email) = 1;Code language: SQL (Structured Query Language) (sql)輸出
email
-----------------------------------
[email protected]
jose [email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]Code language: SQL (Structured Query Language) (sql)在此示例中,我們在 WHERE 子句中使用 POSITION 函式來篩選出 email 列中字母 j 是第一個字元的行。
將 POSITION 函式與 CASE 表示式結合使用 #
以下查詢使用 POSITION 函式與 CASE 表示式來標記電話號碼以 555 開頭的員工。
SELECT
phone_number,
CASE
WHEN POSITION('515' IN phone_number) > 0 THEN 'Starts with 515'
ELSE 'Does not start with 515'
END AS status
FROM
employees;Code language: SQL (Structured Query Language) (sql)輸出
phone_number | status
---------------+-------------------------
515-123-4567 | Starts with 515
515-123-4568 | Starts with 515
515-123-4569 | Starts with 515
590-423-4567 | Does not start with 515
590-423-4568 | Does not start with 515
...Code language: SQL (Structured Query Language) (sql)摘要 #
- 使用
POSITION函式返回子字串在輸入字串中首次出現的位置(基於 1)。 - 如果子字串在輸入字串中不可用,
POSITION函式將返回零。
資料庫 #
本教程是否有幫助?