SQL: Combine Select count(*) from multiple tables

后端 未结 8 623
迷失自我
迷失自我 2020-12-08 13:08

How do you combine multiple select count(*) from different table into one return?

I have a similar sitiuation as this post

but I want one return.

I t

相关标签:
8条回答
  • 2020-12-08 13:51

    you could name all fields and add an outer select on those fields:

    SELECT A, B, C FROM ( your initial query here ) TableAlias
    

    That should do the trick.

    0 讨论(0)
  • 2020-12-08 13:52

    Basically you do the counts as sub-queries within a standard select.

    An example would be the following, this returns 1 row, two columns

    SELECT
     (SELECT COUNT(*) FROM MyTable WHERE MyCol = 'MyValue') AS MyTableCount,
     (SELECT COUNT(*) FROM YourTable WHERE MyCol = 'MyValue') AS YourTableCount,
    
    0 讨论(0)
  • 2020-12-08 13:52
    select sum(counts) from (
    select count(1) as counts from foo 
    union all
    select count(1) as counts from bar)
    
    0 讨论(0)
  • 2020-12-08 13:54

    For oracle:

    select( 
    select count(*) from foo1 where ID = '00123244552000258'
    +
    select count(*) from foo2 where ID = '00123244552000258'
    +
    select count(*) from foo3 where ID = '00123244552000258'
    ) total from dual;
    
    0 讨论(0)
  • 2020-12-08 13:57

    I'm surprised no one has suggested this variation:

    SELECT SUM(c)
    FROM (
      SELECT COUNT(*) AS c FROM foo1 WHERE ID = '00123244552000258'
      UNION ALL
      SELECT COUNT(*) FROM foo2 WHERE ID = '00123244552000258'
      UNION ALL
      SELECT COUNT(*) FROM foo3 WHERE ID = '00123244552000258'
    );
    
    0 讨论(0)
  • 2020-12-08 14:05
    SELECT 
    (select count(*) from foo1 where ID = '00123244552000258')
    +
    (select count(*) from foo2 where ID = '00123244552000258')
    +
    (select count(*) from foo3 where ID = '00123244552000258')
    

    This is an easy way.

    0 讨论(0)
提交回复
热议问题