实现说明
实际执行的是 SELECT / CREATE——orders、customers、recent_orders、information_schema.routines 是涉及的对象。
真正干活的子句:通过 一个 JOIN 按连接条件合并多张表的行;WHERE 把语句的作用范围收窄到满足条件的行;用 SUM 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;LIMIT 限制返回行数。
常见问题
这段 SQL 会碰到哪些对象?
引用的是 orders、customers、recent_orders、information_schema.routines,一个 个 JOIN 把它们连起来。
核心语句
CREATE OR REPLACE FUNCTION recent_orders(p_limit integer)
RETURNS TABLE (order_id bigint, customer text, total numeric, placed_at timestamptz)
LANGUAGE sql
STABLE
AS $$
SELECT o.id, c.name, o.total, o.placed_at
FROM orders o
JOIN customers c ON c.id = o.customer_id
ORDER BY o.placed_at DESC
LIMIT p_limit;
$$;
SELECT routine_name, data_type
FROM information_schema.routines
WHERE routine_name = 'recent_orders';
SELECT customer, SUM(total) AS spent
FROM recent_orders(50)
GROUP BY customer
ORDER BY spent DESC;
代码示例
-- RETURNS TABLE:把查询封装成可参数化的“视图函数”
CREATE OR REPLACE FUNCTION recent_orders(p_limit integer)
RETURNS TABLE (order_id bigint, customer text, total numeric, placed_at timestamptz)
LANGUAGE sql
STABLE
AS $$
SELECT o.id, c.name, o.total, o.placed_at
FROM orders o
JOIN customers c ON c.id = o.customer_id
ORDER BY o.placed_at DESC
LIMIT p_limit;
$$;
-- 像表一样在 FROM 中使用,并可继续过滤
SELECT * FROM recent_orders(5);
SELECT customer, SUM(total) AS spent
FROM recent_orders(50)
GROUP BY customer
ORDER BY spent DESC;
-- 与视图的差异:函数可以接收参数
SELECT routine_name, data_type
FROM information_schema.routines
WHERE routine_name = 'recent_orders';