📜  MySQL 中的 SUBSTRING()函数(1)

📅  最后修改于: 2023-12-03 14:44:28.363000             🧑  作者: Mango

MySQL 中的 SUBSTRING()函数

在 MySQL 中,SUBSTRING() 函数用于在字符串中提取指定位置的子字符串。

语法
SUBSTRING(string, start_position, length)

以下是参数的含义:

  • string:要提取子字符串的字符串
  • start_position:要提取子字符串的起始位置
  • length:要提取的子字符串的长度,可选参数。如果未指定,则 SUBSTRING() 函数将返回从起始位置到字符串末尾的所有字符。
示例

假设我们有以下 employees 表格:

| employee_id | first_name | last_name | email | hire_date | | ----------- | ---------- | --------- | --------------------------- | ---------- | | 1 | John | Doe | johndoe@company.com | 2010-01-01 | | 2 | Jane | Smith | janesmith@company.com | 2012-05-01 | | 3 | Bob | Johnson | bobjohnson@company.com | 2015-10-01 | | 4 | Mary | Lee | marylee@company.com | 2017-01-01 | | 5 | George | Brown | georgebrown@company.com | 2018-03-01 |

以下是 SUBSTRING() 函数的示例:

  1. 提取第一个电话号码的前三个数字:
SELECT SUBSTRING('123-456-7890', 1, 3);
-- 返回 '123'
  1. 提取 employees 表格中每个员工的前两个字符的名字:
SELECT SUBSTRING(first_name, 1, 2) AS initials FROM employees;
-- 返回以下结果:
-- initials
-- J
-- Ja
-- Bo
-- Ma
-- Ge
  1. 提取最新雇用的三名员工的电子邮件的最后四个字符:
SELECT SUBSTRING(email, -4) AS domain FROM employees ORDER BY hire_date DESC LIMIT 3;
-- 返回以下结果:
-- domain
-- com
-- com
-- com
注意事项
  • start_position 参数是从 1 开始计数的,而不是从 0 开始计数的。
  • 如果 length 参数太大,将超出字符串的长度,则 SUBSTRING() 函数将返回从起始位置到字符串末尾的所有字符。
  • 如果 start_position 参数大于字符串的长度,则 SUBSTRING() 函数将返回一个空字符串。