在 SQL 中,SUBSTRING()
函数用于从字符串中提取子字符串。
示例
-- extract the first 3 characters from the first names of each customer
SELECT customer_id, SUBSTRING(first_name, 1, 3) AS first_name_short
FROM Customers;
在这里,我们使用 SUBSTRING()
提取每个客户名字的前三个字符。
该函数接受三个参数:字符串列、起始位置和子字符串的长度。
结合 JOIN 使用 SUBSTRING()
在 SQL 中,SUBSTRING()
函数也可以用于更复杂的场景,例如与 JOIN 操作结合使用。
让我们看一个例子。
-- extract part of item names in order details
SELECT o.order_id, SUBSTRING(o.item, 1, 5) AS item_short, o.amount
FROM Orders o
JOIN Customers c ON o.customer_id = c.customer_id
WHERE c.country = 'UK';
在此 SQL 命令中,我们正在连接 Customers 和 Orders 表,并提取英国客户订单中每个商品名称的前五个字符。
访问 SQL JOIN 了解更多关于 SQL 中 JOIN
子句的信息。
在 WHERE 子句中使用 SUBSTRING()
我们可以使用 SUBSTRING()
函数与 WHERE
子句结合,根据特定的字符串模式过滤数据。例如,
-- select customers with 'Jo' at the beginning of their first name
SELECT customer_id, first_name, last_name
FROM Customers
WHERE SUBSTRING(first_name, 1, 2) = 'Jo';
在这里,SQL 命令过滤 Customers 表,只包含名字以 Jo
开头的客户。