【问题标题】:count from multiple tables in MySQL/oracle从 MySQL/oracle 中的多个表中计数
【发布时间】:2018-09-22 02:22:02
【问题描述】:

有 4 个表:A,B,C,D
有一个 id:4(input)
查询应该打印 id 在表中出现的次数

前:

in table A id:4 occurs 5 times
in table B id:4 occurs 7 times
in table C id:4 occurs 3 times
in table D id:4 occurs 1 times

输出:

Table name       No of occurence

A                   5
B                   7
C                   3
D                   1

【问题讨论】:

    标签: mysql sql oracle hibernate


    【解决方案1】:

    你可以试试这样的:

    select 'A', count(*) from a where id = 4
    union all
    select 'B', count(*) from b where id = 4
    union all
    select 'C', count(*) from c where id = 4
    union all
    select 'D', count(*) from d where id = 4
    

    【讨论】:

      【解决方案2】:
      select id as Name,count(id) as occurence from tableA where id = 4 group by id
      union all
      select id as Name,count(id) as occurence from tableB where id = 4 group by id
      union all
      select id as Name,count(id) as occurence from tableC where id = 4 group by id
      union all
      select id as Name,count(id) as occurence from tableD where id = 4 group by id
      

      【讨论】:

        【解决方案3】:

        执行union all

        select 'A' as Name, count(*) as occurence from tablea where id = ?
        union all
        select 'B' as Name, count(*) as occurence from tableb where id = ?
        union all
        select 'C' as Name, count(*) as occurence from tablec where id = ?
        union all
        select 'D' as Name, count(*) as occurence from tabled where id = ?
        

        【讨论】:

        • 如果需要空格,可以引用名称:select count(*) as 'No of occurance'
        猜你喜欢
        • 2019-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-02
        • 1970-01-01
        • 1970-01-01
        • 2011-09-19
        相关资源
        最近更新 更多