← 中文资源

简体中文版本

split_part 提取分隔字段

split_part 按分隔符取第 N 段:1 起始,负数从末尾倒数(PG 14+),超出实际段数返回空串而不报错,适合解析主机名与编码标签。

阅读英文原文

实现说明

这条语句是 SELECT,涉及 hosts。 把语句拆开看,工作部件是:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它。

常见问题

这个脚本里出现了哪些表?

hosts。

核心语句

WITH hosts AS (
    SELECT * FROM (VALUES
        ('db-1.internal.example.com'),
        ('cache.example.com'),
        ('localhost')
    ) AS t(host)
)
SELECT
    host,
    split_part(host, '.', 1) AS first_label,
    split_part(host, '.', -1) AS tld,
    split_part(host, '.', 5) AS missing
FROM hosts;

代码示例

WITH hosts AS (
    SELECT * FROM (VALUES
        ('db-1.internal.example.com'),
        ('cache.example.com'),
        ('localhost')
    ) AS t(host)
)
SELECT
    host,
    -- fields count from 1
    split_part(host, '.', 1) AS first_label,
    -- negative indexes count from the end (PG 14+)
    split_part(host, '.', -1) AS tld,
    -- past the last field an empty string returns, no error
    split_part(host, '.', 5) AS missing
FROM hosts;