Select count(*) from multiple tables

2019-01-03 00:55发布

How can I select count(*) from two different tables (call them tab1 and tab2) having as result:

Count_1   Count_2
123       456

I've tried this:

select count(*) Count_1 from schema.tab1 union all select count(*) Count_2 from schema.tab2

But all I have is:

Count_1
123
456

标签: sql oracle count
18条回答
虎瘦雄心在
2楼-- · 2019-01-03 01:42

As I can't see any other answer bring this up.

If you don't like sub-queries and have primary keys in each table you can do this:

select count(distinct tab1.id) as count_t1,
       count(distinct tab2.id) as count_t2
    from tab1, tab2

But performance wise I believe that Quassnoi's solution is better, and the one I would use.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-03 01:42

If the tables (or at least a key column) are of the same type just make the union first and then count.

select count(*) 
  from (select tab1key as key from schema.tab1 
        union all 
        select tab2key as key from schema.tab2
       )

Or take your satement and put another sum() around it.

select sum(amount) from
(
select count(*) amount from schema.tab1 union all select count(*) amount from schema.tab2
)
查看更多
smile是对你的礼貌
4楼-- · 2019-01-03 01:46
select (select count(*) from tab1) count_1, (select count(*) from tab2) count_2 from dual;
查看更多
霸刀☆藐视天下
5楼-- · 2019-01-03 01:47
SELECT  (
        SELECT COUNT(*)
        FROM   tab1
        ) AS count1,
        (
        SELECT COUNT(*)
        FROM   tab2
        ) AS count2
FROM    dual
查看更多
男人必须洒脱
6楼-- · 2019-01-03 01:47
select @count = sum(data) from
(
select count(*)  as data from #tempregion
union 
select count(*)  as data from #tempmetro
union
select count(*)  as data from #tempcity
union
select count(*)  as data from #tempzips
) a
查看更多
相关推荐>>
7楼-- · 2019-01-03 01:48
Declare @all int
SET @all = (select COUNT(*) from tab1) + (select count(*) from tab2)
Print @all

or

SELECT (select COUNT(*) from tab1) + (select count(*) from tab2)
查看更多
登录 后发表回答