选择具有多个表的distinct

时间:2016-06-01 12:48:58

标签: sql firebird firebird2.5

我尝试使用RDB $ Fields和RDB $ Relation_Fields获取按关系分组的字段列表。遵循SQL:

select distinct
         RDB$relation_Fields.RDB$relation_name as "Relation Name" ,
         RDB$relation_Fields.RDB$field_name    as "Field Name   " ,
         (select RDB$Fields.RDB$Field_Type     as "Field Type"
          from   RDB$Fields
          where  RDB$Fields.rdb$Field_Name = 
                 RDB$relation_Fields.RDB$Field_Name)
from
   RDB$fields         ,
   RDB$relation_Fields
where
              RDB$relation_Fields.RDB$relation_name = 'Database_Table'      and
   substring (                    RDB$relation_name from 1 for 4) <> 'IDE$' and
   substring (                    RDB$relation_name from 1 for 4) <> 'MON$'                 substring (                    RDB$relation_name from 1 for 4) <> 'RDB$'
   order by
                           RDB$relation_name,
                           RDB$relation_Fields.rdb$field_name

我应该

    Relation Name  Field Name Field Type
    -------------  ---------- ----------
    Database_Table Field1     TypeX
    Database_Table Field2     TypeY
    ...           ...        ...

相反,我正在

    Relation Name  Field Name Field Type
    -------------  ---------- ----------
    Database_Table Field1     <null>
    Database_Table Field2     <null>
    ...            ...        <null>

请告诉我正确的SQL。

1 个答案:

答案 0 :(得分:3)

首先,需要加入表格。否则你会得到一个交叉连接的结果。

此外,您不需要fieldtype列的相关子查询,因为表已经加入(假设您添加了连接条件 - 我根据Thorsten的注释添加了它)。

select rf.RDB$relation_name as "Relation Name" ,
       rf.RDB$field_name    as "Field Name   " ,
       f.RDB$Field_Type     as "Field Type"
from RDB$fields f
JOIN RDB$relation_Fields rf on f.RDB$FIELD_NAME = rf.RDB$FIELD_SOURCE
where rf.RDB$relation_name = 'Database_Table'                
and substring (rf.RDB$relation_name from 1 for 4) not in ('IDE$','MON$','RDB$')
order by rf.RDB$relation_name, rf.RDB$field_name