1、建表以及外键关系
- 建表
CREATE TABLE "public"."test_01" (
"id" int4 NOT NULL,
"test_02_id" int4 NOT NULL,
CONSTRAINT "test_01_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "public"."test_02" (
"id" int4 NOT NULL,
"test_01_id" int4 NOT NULL,
CONSTRAINT "test_02_pkey" PRIMARY KEY ("id")
);
- 外键
test_01和test_02的外键名称相同
alter table public.test_01
add constraint test_fk
foreign key (test_02_id) references public.test_02 (id);
alter table public.test_02
add constraint test_fk
foreign key (test_01_id) references public.test_01 (id);
2、查询外键信息
- information_schema.table_constraints
select * from information_schema.table_constraints a where a.constraint_type = 'FOREIGN KEY' AND a.constraint_schema = 'public';

- information_schema.key_column_usage
select * from information_schema.key_column_usage a where a.constraint_schema = 'public';

- information_schema.constraint_column_usage
select * from information_schema.constraint_column_usage a where a.constraint_schema = 'public';

- 查询test_01的外键信息
SELECT
a.constraint_name,
a.table_name AS table_name,
b.column_name AS name,
c.table_schema AS f_table_schema,
c.table_name AS f_table_name,
c.column_name AS f_column_name
FROM
information_schema.table_constraints a
INNER JOIN information_schema.key_column_usage AS b ON a.constraint_name = b.constraint_name AND a.constraint_schema = b.constraint_schema AND a.table_name = b.table_name
INNER JOIN information_schema.constraint_column_usage AS c ON c.constraint_name = a.constraint_name AND a.constraint_schema = c.constraint_schema
WHERE a.constraint_type = 'FOREIGN KEY' AND a.table_name = 'test_01' AND a.constraint_schema = 'public'

3、问题
查询test_01的外键信息正确只有一条数据,结果出来两条,第二条数据是错误的。如何对上述SQL进行处理?
博客围绕PostgreSQL数据库展开,介绍了建表及外键关系,如test_01和test_02外键名称相同;还说明了查询外键信息的方法,使用information_schema相关表查询test_01外键信息。最后提出查询test_01外键信息结果异常的问题及处理需求。

2267

被折叠的 条评论
为什么被折叠?



