实现说明
实际执行的是 SELECT / INSERT / CREATE——deployments 是涉及的对象。
从子句角度看,用到了:必填列上的 NOT NULL 限定。
常见问题
这里涉及哪些关系(表/CTE)?
引用的是 deployments。
核心语句
INSERT INTO deployments VALUES
('gateway', ARRAY['us-1', 'eu-1', 'us-1', 'ap-1']),
('billing', ARRAY['eu-1', 'eu-1']);
SELECT service,
cardinality(array_positions(replicas, 'eu-1')) AS eu_count
FROM deployments;
CREATE TABLE deployments (
service text NOT NULL,
replicas text[] NOT NULL
);
代码示例
CREATE TABLE deployments (
service text NOT NULL,
replicas text[] NOT NULL
);
INSERT INTO deployments VALUES
('gateway', ARRAY['us-1', 'eu-1', 'us-1', 'ap-1']),
('billing', ARRAY['eu-1', 'eu-1']);
-- array_positions:该值出现的全部下标(找不到返回空数组,不是 NULL)
SELECT service,
array_positions(replicas, 'us-1') AS us_slots
FROM deployments;
-- 也能搜 NULL 元素:比较用 IS NOT DISTINCT FROM 语义
SELECT array_positions(ARRAY['x', NULL::text, 'x'], NULL) AS null_slots;
-- array_position 只给第一处下标;没有则返回 NULL
SELECT service,
array_position(replicas, 'ap-1') AS first_ap
FROM deployments;
-- 组合用法:命中数用 cardinality 数
SELECT service,
cardinality(array_positions(replicas, 'eu-1')) AS eu_count
FROM deployments;