实现说明
这条语句是 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;