如需检查缺少相应主键的外键,请运行以下命令:
代码示例
WITH q AS ( SELECT conrelid::regclass AS fk_table, confrelid::regclass AS pk_table, format('(%s)',(select string_agg(format('fk.%I', attname), ', ') FROM pg_attribute a JOIN unnest(conkey) ia(nr) ON ia.nr = a.attnum WHERE attrelid = conrelid)) AS fk_fields, format('(%s)',(select string_agg(format('pk.%I', attname), ', ') FROM pg_attribute a JOIN unnest(confkey) ia(nr) ON ia.nr = a.attnum WHERE attrelid = confrelid)) AS pk_fields, pg_get_constraintdef(oid) FROM pg_constraint WHERE contype='f' ) SELECT format( $sql$ DO $$ BEGIN RAISE NOTICE 'checking Foreign Key %3$s%1$s ==> %4$s%2$s'; END;$$; SELECT %1$s, %2$s FROM %3$s AS fk LEFT JOIN %4$s AS pk ON %1$s = %2$s WHERE %2$s IS NULL AND %1$s IS NOT NULL /* any NULL on FK side bypasses FK constraint by design */ /* use limit for testing, or detecting that "there is a problem in this table */ -- LIMIT 10 $sql$, fk_fields, pk_fields, fk_table, pk_table ) FROM q \gexec
该脚本的输出将如下所示。如果没有输出,则表示没有违规行为,并且您已成功重新构建索引。
输出
id | pk_id ----+------- | 4 (1 row)
在上述输出中,第一列显示主键列(在此示例中是名为 id
的列)。第二列是外键的引用列。这意味着存在 pk_id=4
行,其父主键不存在。您可以确定这些键是否有效,如果无效,则可以删除。