使用 PostgreSQL SQL 查询 Fabric HorizonDB 中的操作数据。 本文使用由 sample-data 快速入门创建的 horizon_sample 架构。
Important
Fabric HorizonDB 处于公开预览阶段。 功能、限制和行为可能会在正式发布前发生变化。 有关详细信息,请参阅 Microsoft Fabric 预览功能。
Prerequisites
- 一个 HorizonDB 数据库。
- 使用来自 Load 示例数据 或您自己的等效表中的数据。
- 以数据库创建者身份登录,这是当前预览版中唯一可以连接到 PostgreSQL 的身份。
检查行
从一个有界、有序的结果开始:
SELECT
order_reference,
order_date,
status,
total
FROM horizon_sample.orders
ORDER BY order_date DESC, order_reference
LIMIT 100;
PostgreSQL 无法保证没有 ORDER BY 时的行顺序。
连接客户和订单
SELECT
order_row.order_reference,
customer.customer_name,
customer.segment,
order_row.order_date,
order_row.status,
order_row.total
FROM horizon_sample.orders AS order_row
JOIN horizon_sample.customers AS customer
ON customer.customer_id = order_row.customer_id
ORDER BY order_row.order_reference;
模式限定使目标明确,避免依赖 search_path。
使用参数筛选
应用程序应将值作为驱动程序参数传递。 在交互式查询中,您可以使用预备语句:
PREPARE orders_by_status (text) AS
SELECT
order_reference,
order_date,
total
FROM horizon_sample.orders
WHERE status = $1
ORDER BY order_date DESC;
EXECUTE orders_by_status ('open');
DEALLOCATE orders_by_status;
预处理语句的生命周期与会话绑定。 不要以为它能在暂停或中断性切换后存活下来。
聚合数据
SELECT
customer.segment,
count(order_row.order_id) AS order_count,
coalesce(sum(order_row.total), 0) AS order_total,
coalesce(avg(order_row.total), 0) AS average_order_total
FROM horizon_sample.customers AS customer
LEFT JOIN horizon_sample.orders AS order_row
ON order_row.customer_id = customer.customer_id
GROUP BY customer.segment
ORDER BY customer.segment;
左连接即使在客户没有订单时,也会保留一个分段。
分析查询计划
使用 EXPLAIN 检查计划的操作而不执行查询:
EXPLAIN (COSTS, VERBOSE)
SELECT
order_reference,
order_date,
total
FROM horizon_sample.orders
WHERE customer_id = 1
ORDER BY order_date DESC;
请谨慎使用 EXPLAIN (ANALYZE, BUFFERS) ,因为它会执行该语句。 除非你有意想要更改数据并用合适的事务包裹,否则不要在数据变更语句上使用 ANALYZE 。
更新事务中的数据
BEGIN;
UPDATE horizon_sample.orders
SET status = 'processing'
WHERE order_reference = 'ORD-1001'
AND status = 'open'
RETURNING order_reference, status;
COMMIT;
状态谓词使过渡具有条件性。 如果命令没有返回行,说明另一个会话或之前的运行可能已经更改了该订单。
对于可重试的应用工作流,请使用稳定的业务密钥和幂等状态转换。 在提交过程中失去连接后,不要盲目重放事务。
查询元数据
查找客户表:
SELECT
schemaname AS schema_name,
tablename AS table_name,
tableowner AS table_owner
FROM pg_catalog.pg_tables
WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
ORDER BY schemaname, tablename;
查找最大的客户表:
SELECT
statistics.schemaname AS schema_name,
statistics.relname AS table_name,
pg_total_relation_size(statistics.relid) AS total_bytes,
pg_size_pretty(pg_total_relation_size(statistics.relid)) AS total_size
FROM pg_catalog.pg_statio_user_tables AS statistics
ORDER BY total_bytes DESC
LIMIT 20;
排查查询结果
| 问题 | 检查 |
|---|---|
| 没有排队 | 验证筛选条件、事务可见性,以及示例数据是否已提交。 |
| 关系不存在 | 核实数据库、架构、名称和引号标识符大小写。 |
| 访问被拒绝 | 确认您是数据库创建者,检查对象所有权,并确认操作是否受支持。 |
| 查询被阻止 |
如果允许,请检查pg_stat_activity和pg_blocking_pids()。 |
| 数据与 SQL 分析端点不同 | 镜像是异步的;比较时间戳和镜像状态。 |
| 空闲时间后连接失败 | 在数据库恢复时使用有界重试重新连接。 |