SQL将两个查询合并为一个

时间:2012-03-01 22:34:39

标签: sql oracle

您好我想加入这两个查询,最终得到一个具有表名,表中列数和外键列数的查询。

此查询生成表名和列数

select t.table_name,  count(t.table_name)
from all_constraints  t 
where owner = 'PARRANDEROS' group by t.table_name;

另一个查询外键计数。

select table_name,  count(constraint_type)
from all_constraints  
where owner = 'PARRANDEROS' and constraint_type ='R'group by table_name;

如何加入这两个查询?我正在使用oracle DB。

编辑:有些人告诉我,我没有选择每张表中的列数。那么如何计算数据库中每个表的数量呢?

2 个答案:

答案 0 :(得分:2)

您可以合并查询

SELECT table_name, 
       COUNT(*) number_of_constraints,
       SUM( CASE WHEN constraint_type = 'R' 
                 THEN 1
                 ELSE 0
              END) number_of_fk_constraints
  FROM all_constraints
 WHERE owner = 'PARRANDEROS'
 GROUP BY table_name

这不会检索表中的列数,但不会检索任何现有查询。它确实返回表上定义的约束数。这不会检索表中作为外键约束一部分的列数,但是除非我们假设所有外键约束都在单个列上定义而不是可能在复合键上定义,否则它不会检索第二个查询。

如果要计算表中的列数和表中的外键约束数(请注意,这可能与外键约束中涉及的列数不同)

SELECT t.table_name,
       (SELECT COUNT(*)
          FROM all_tab_cols cols
         WHERE cols.owner = t.owner
           AND cols.table_name = t.table_name) number_of_columns,
       (SELECT COUNT(*)
          FROM all_constraints cons
         WHERE constraint_type = 'R'
           AND cons.owner = t.owner
           AND cons.table_name = t.table_name) number_of_constraints
  FROM all_tables t
 WHERE t.owner = 'PARRANDEROS'
 GROUP BY t.table_name

答案 1 :(得分:0)

好的,关键是你要从ALL_TAB_COLUMNS中获取列名:

SELECT table_name, COUNT(column_name)
  FROM all_tab_columns
 WHERE owner = 'PARRANDEROS'
 GROUP BY table_name

为了获得对它们也有外键约束的列数,您还必须加入ALL_CONS_COLUMNS和ALL_CONSTRAINTS。这些应该是外连接,因为列可能根本没有任何约束,并且使用DISTINCT,因为列上可能有多个约束。

SELECT a.table_name, COUNT(DISTINCT a.column_name) AS column_cnt
     , COUNT( DISTINCT DECODE(c.constraint_type, 'R', a.column_name || '|' || c.constraint_name, null) ) AS fk_cnt
  FROM all_tab_columns a, all_cons_columns b, all_constraints c
 WHERE a.owner = 'PARRANDEROS'
   AND a.owner = b.owner(+)
   AND a.table_name = b.table_name(+)
   AND a.column_name = b.column_name(+)
   AND b.owner = c.owner(+)
   AND b.table_name = c.table_name(+)
   AND b.constraint_name = c.constraint_name(+)
 GROUP BY a.table_name

希望这有帮助。