mySQL与计算行的联合

时间:2013-07-08 11:31:13

标签: mysql sql sum

我有类似的查询:

select 'table_1', count(*)
from table_1
union 
select 'table_2', count(*)
from table_2
union 
select 'table_n', count(*)
from table_n

返回每个表的总行数(n个表)。

  table_1 | 100
  table_2 | 150
  table_n | 400

我想知道是否有一个mysql函数可以在最后添加一条新记录,使所有行的总和如下:

  table_1 | 100
  table_2 | 150
  table_n | 400
  total   | 650

有没有办法在没有使用过程的情况下在mySQL(版本5.5)中执行此操作? (例如,如果支持,则在sql中使用变量)

4 个答案:

答案 0 :(得分:2)

     select ifnull(table_name,'Total'), sum(row_count)
       from (select 'table_1' table_name, count(*) row_count
            from table_1
            union 
            select 'table_2' table_name, count(*) row_count
            from table_2
            union 
            select 'table_n' table_name, count(*) row_count
            from table_n ) temp
   group by table_name with rollup;

答案 1 :(得分:1)

也许使用WITH ROLLUP: -

SELECT TableName, TableCount
FROM
(
    SELECT 'table_1' AS TableName, COUNT(*) AS TableCount
    FROM table_1
    union 
    SELECT 'table_2' AS TableName, COUNT(*) AS TableCount
    FROM table_2
    SELECT 
    select 'table_n' AS TableName, COUNT(*) AS TableCount
    FROM table_n
) Sub1
GROUP BY TableName, TableCount WITH ROLLUP

答案 2 :(得分:1)

如果您只在行数之后,则应使用系统表。 这样做的好处是,如果您准备查询,则不必对表名进行硬编码,因为这些可以作为参数传递:

select ifnull(table_name,'Total') as table_name, sum(table_rows) as table_rows
from (
SELECT
    TABLE_NAME, 
    TABLE_ROWS 
FROM 
    INFORMATION_SCHEMA.TABLES 
WHERE
    TABLE_NAME IN ('tOne', 'tTwo', 'tThree') 
) temp
group by table_name with rollup;

答案 3 :(得分:0)

select 'table_1', count(*)
from table_1
union 
select 'table_2', count(*)
from table_2
union 
select 'table_n', count(*)
from table_n
union 
select 'total', sum(a.count) 
from (
   select 'table_1', count(*)
   from table_1
   union 
   select 'table_2', count(*)
   from table_2
   union 
   select 'table_n', count(*)
   from table_n
) a