如何在Firebird中获取外键引用表

问题描述 投票:0回答:2

有一个table1有table2的外键(一个table2到多个table1)。如何获取table2字段列表:

"table2.f1"
"table2.f2"
"table2.f3"

只需提供“table1.f3”(具有表2的外键)。如何从系统表中选择它?

firebird
2个回答
12
投票

列出 FK 表和字段引用的所有内容。

SELECT
    detail_index_segments.rdb$field_name AS field_name,
    master_relation_constraints.rdb$relation_name AS reference_table,
    master_index_segments.rdb$field_name AS fk_field

FROM
    rdb$relation_constraints detail_relation_constraints
    JOIN rdb$index_segments detail_index_segments ON detail_relation_constraints.rdb$index_name = detail_index_segments.rdb$index_name 
    JOIN rdb$ref_constraints ON detail_relation_constraints.rdb$constraint_name = rdb$ref_constraints.rdb$constraint_name -- Master indeksas
    JOIN rdb$relation_constraints master_relation_constraints ON rdb$ref_constraints.rdb$const_name_uq = master_relation_constraints.rdb$constraint_name
    JOIN rdb$index_segments master_index_segments ON master_relation_constraints.rdb$index_name = master_index_segments.rdb$index_name 

WHERE
    detail_relation_constraints.rdb$constraint_type = 'FOREIGN KEY'
    AND detail_relation_constraints.rdb$relation_name = :table_name

3
投票

获取特定表的外键引用的all外键目标(即主键或唯一键)的查询可以使用下面的查询来查询。我认为这将为您提供足够的信息来获取特定专栏的信息:

select 
 PK.RDB$RELATION_NAME as PKTABLE_NAME
,ISP.RDB$FIELD_NAME as PKCOLUMN_NAME
,FK.RDB$RELATION_NAME as FKTABLE_NAME
,ISF.RDB$FIELD_NAME as FKCOLUMN_NAME
,(ISP.RDB$FIELD_POSITION + 1) as KEY_SEQ
,RC.RDB$UPDATE_RULE as UPDATE_RULE
,RC.RDB$DELETE_RULE as DELETE_RULE
,PK.RDB$CONSTRAINT_NAME as PK_NAME
,FK.RDB$CONSTRAINT_NAME as FK_NAME
from
 RDB$RELATION_CONSTRAINTS PK
,RDB$RELATION_CONSTRAINTS FK
,RDB$REF_CONSTRAINTS RC
,RDB$INDEX_SEGMENTS ISP
,RDB$INDEX_SEGMENTS ISF
WHERE FK.RDB$RELATION_NAME = ? and 
 FK.RDB$CONSTRAINT_NAME = RC.RDB$CONSTRAINT_NAME 
and PK.RDB$CONSTRAINT_NAME = RC.RDB$CONST_NAME_UQ 
and ISP.RDB$INDEX_NAME = PK.RDB$INDEX_NAME 
and ISF.RDB$INDEX_NAME = FK.RDB$INDEX_NAME 
and ISP.RDB$FIELD_POSITION = ISF.RDB$FIELD_POSITION 
order by 1, 5 

此查询是 Jaybird 中使用的查询的改编版本,请参阅

AbstractDatabaseMetaData

© www.soinside.com 2019 - 2024. All rights reserved.