mysql在一个请求中计算几个表

时间:2013-02-12 07:17:34

标签: mysql bash

我有以下输出:

    root@localhost [~]# mysql -e "SELECT TABLE_ROWS from information_schema.Tables where TABLE_SCHEMA= 'testdb' && TABLE_NAME = 'requests';"
    +------------+
    | TABLE_ROWS |
    +------------+
    |    9566846 |
    +------------+

    root@localhost [~]# mysql -e "select count(*) from testdb.requests where created_at like '2012%';"
    +----------+
    | count(*) |
    +----------+
    |   301438 |
    +----------+
    root@localhost [~]# mysql -e "select count(*) from testdb.requests where created_at like '2013%';"
    +----------+
    | count(*) |
    +----------+
    |    24917 |
    +----------+

如何更好,使用mysql请求对一个请求执行相同操作,以获得新输出,如

    +------------------+-----------------------+
    | year             | count(*)              |
    +------------------+-----------------------+
    | 2009             | 1066268               |
    | 2010             | 6799553               |
    | 2011             | 1374685               |
    | 2012             | 301438                |
    | 2013             | 24917                 |
    | total            | 9566846               |
    +------------------+-----------------------+

提前谢谢你,Evgheni

3 个答案:

答案 0 :(得分:1)

您可以尝试使用群组声明

select 
    DATE_FORMAT(created_at, '%d') as year, 
    count(*) as count
from
    testdb.requests
group by year;

答案 1 :(得分:1)

尝试使用聚合函数 -

SELECT
  YEAR(created_at) yesr,
  COUNT(*) cnt
FROM
  testdb.requests
GROUP BY year;

统计使用WITH ROLLUP修饰符 -

SELECT
  YEAR(created_at) yesr,
  COUNT(*) cnt
FROM
  testdb.requests
GROUP BY year WITH ROLLUP;

答案 2 :(得分:1)

试试这个

SELECT YEAR(created_at) AS `year`,
       COUNT(*) AS `count` 
  FROM testdb.requests 
 GROUP BY YEAR(created_at)
 UNION ALL
SELECT 'total' AS `year`, 
       TABLE_ROWS AS `count`
  FROM information_schema.Tables 
 WHERE TABLE_SCHEMA= 'testdb' AND 
       TABLE_NAME = 'requests'

SELECT YEAR(created_at) AS `year`,
       COUNT(*) AS `count` 
  FROM testdb.requests 
 GROUP BY YEAR(created_at)
 UNION ALL
SELECT 'total' AS `year`, 
       COUNT(*) AS `year`
  FROM testdb.requests 

它产生如下输出:

+-------+-------+
| year  | count |
+-------+-------+
| 2012  |     6 |
| 2013  |     7 |
| total |    13 |
+-------+-------+

这是sqlfiddle