← 中文资源

简体中文版本

INFORMATION_SCHEMA 自省

用 information_schema.columns 与 table_constraints 查列清单和外键关系:标准视图跨库可移植,不用对系统目录写死表名。

阅读英文原文

实现说明

这个文件依次执行 SELECT 语句,涉及 information_schema.columns、information_schema.table_constraints、information_schema.key_column_usage、information_schema.constraint_column_usage。 把语句拆开看,工作部件是:通过 2 个 JOIN 把几张表的行按条件接到一起;WHERE 决定这条语句会作用到哪些行;ORDER BY 固定了输出顺序。

使用要点

  • 2 个 JOIN 会让中间结果按表规模相乘,上生产规模的数据前先确认连接键有索引。

常见问题

它引用了哪些表或 CTE?

information_schema.columns、information_schema.table_constraints、information_schema.key_column_usage、information_schema.constraint_column_usage,通过 2 个 JOIN 连接。

核心语句

SELECT
    column_name,
    data_type,
    is_nullable,
    column_default
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'orders'
ORDER BY ordinal_position;

代码示例

-- 查一张表的列清单:标准 SQL 的 information_schema,跨库可移植
SELECT
    column_name,
    data_type,
    is_nullable,
    column_default
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'orders'
ORDER BY ordinal_position;

-- 外键关系同样可查:谁引用了谁一目了然
SELECT
    tc.constraint_name,
    kcu.column_name,
    ccu.table_name  AS referenced_table,
    ccu.column_name AS referenced_column
FROM information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
  ON tc.constraint_schema = kcu.constraint_schema
 AND tc.constraint_name  = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
  ON ccu.constraint_schema = tc.constraint_schema
 AND ccu.constraint_name  = tc.constraint_name
WHERE tc.constraint_type = 'FOREIGN KEY'
  AND tc.table_schema = 'public'
  AND tc.table_name = 'orders';