2016-11-04 68 views
1

我選擇了少數表的計數,我有一個名爲table_counts的表,它有兩列名爲table_name和table_count的列。我想要將查詢的結果與table_counts表的table_name列結合起來。請看下面的例子。如何加入具有所有計數的另一個表的計數查詢?

select 'Table 1' as table_name, count(*) as table_count_from table_1 
union 
select 'Table 2' as table_name, count(*) as table_count_from table_2 
union 
select 'Table 3' as table_name, count(*) as table_count_from table_3 

------------------ 
++table_counts++++ 
------------------ 
table_name table count 
Table 1  10 
Table 2  20 
Table 3  30 

我必須使用table_name加入兩件事情。如果我缺少一些東西,有人能幫助我嗎?

回答

0

你正在尋找類似的東西?

SELECT * 
    FROM table_counts cnt 
    LEFT OUTER JOIN (select 'Table 1' as table_name, count(*) as table_count_from table_1 
        union 
        select 'Table 2' as table_name, count(*) as table_count_from table_2 
        union 
        select 'Table 3' as table_name, count(*) as table_count_from table_3 
       ) subcnt 
    ON cnt.table_name = subcnt.table_name 
+1

謝謝..這是我需要的。 –