2012-03-01 107 views
0

您好,我想要加入這兩個查詢,最終得到一個具有表名稱,表中的列數和具有外鍵的列數。SQL將兩個查詢合併爲一個

,該查詢產生的表名和列數

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數據庫。

編輯:有人告訴我,我沒有選擇每個表中的列數。那麼如何計算數據庫中每個表的數量?

+1

我不確定我關注。這兩個查詢都不會返回您所說的結果。這兩個查詢都會返回表上的約束條數。它們都不是特定於外鍵的,它們也不與表中的列數或具有外鍵約束的列數有關。你是否假設所有的外鍵約束都在單列而不是複合鍵? – 2012-03-01 22:38:54

+0

對不起,我只是更新第二個查詢,現在它選擇所有與外鍵約束的列。 – serpiente 2012-03-01 22:46:16

+1

您是不是想要從all_tab_columns獲取列計數? – Joey 2012-03-01 22:47:15

回答

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 
0

OK,關鍵是要從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 

希望這會有所幫助。