Domanda

There is a table1 that has foreign key to table2 (one table2 to many table1). How to get list of table2 fields:

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

just by giving "table1.f3" (that has foreign key to table2). How to select this from system tables?

Thank you!

È stato utile?

Soluzione

Lists all referenced by FK tables and fields.

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

Altri suggerimenti

The query to get all foreign key targets (ie primary keys or unique keys) referenced by the foreign keys of a specific table can be queryied using the query below. I think this will give you sufficient information to get it for a specific column:

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 

This query is an adaptation of the one used in Jaybird, see AbstractDatabaseMetaData

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top