1

我有一个类似的查询:

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

4 回答 4

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;
于 2013-07-08T11:55:25.817 回答
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
于 2013-07-08T11:52:03.880 回答
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;
于 2013-07-08T12:18:13.033 回答
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
于 2013-07-08T11:53:42.333 回答