PostgreSQL查询外键信息

博客围绕PostgreSQL数据库展开,介绍了建表及外键关系,如test_01和test_02外键名称相同;还说明了查询外键信息的方法,使用information_schema相关表查询test_01外键信息。最后提出查询test_01外键信息结果异常的问题及处理需求。
1、建表以及外键关系
  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")
);
  1. 外键

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、查询外键信息
  1. information_schema.table_constraints
select * from information_schema.table_constraints a where a.constraint_type = 'FOREIGN KEY' AND a.constraint_schema = 'public';

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

  1. 查询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进行处理?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值