MySQL-垂直连接查询结果

时间:2019-04-23 16:10:17

标签: mysql

我正在尝试创建摘要报告以捕获每日统计信息。基本上我需要类似以下结果:

Table_Name       Updated_Rows       Created_Rows      Date
Table 1          10                 5                 2019-04-23
Table 2          17                 55                2019-04-23

现在,我可以使用基本命令来获取各个值:

select count(*) as created_rows 
from accounts 
where date(updated_at) = date(now())

select count(*) as created_rows 
from accounts 
where date(created_at) = date(now())

还可以使用UNINON ALL组合数据,

(SELECT table_name FROM information_schema.tables where table_name='accounts')
UNION ALL
(select count(*) as created_rows from accounts where date(created_at) = date(now()))
UNION ALL
(select count(*) as updated_rows from accounts where date(updated_at) = date(now()))

无论如何,我得到的输出都是垂直堆叠的,我希望保留标签/列名,并希望为要评估的所有表逐行添加数据。

我确信有一个更简单的方法,但是我似乎找不到找到解决方法。不需要最终查询,只需为我提供指导即可。

3 个答案:

答案 0 :(得分:0)

对于单个表,您可以执行以下操作:

SELECT 'account' AS 'Table_Name'
,      SUM(date(updated_at) = date(now())) 'Updated_Rows' 
,      SUM(date(created_at) = date(now())) 'Created_Rows'
,      date(now()) AS 'Date'
FROM accounts

其中SUM(date(updated_at) = date(now()))

基本相同
 IF(SUM(date(updated_at) = date(now())), 1, 0)

然后从其他具有类似查询的表中得到 UNION ALL 的结果。

答案 1 :(得分:0)

您可以尝试以下操作(未经测试):

select '@x' as table_name,
(select count(*) FROM @x and date(created_at) = date(now())) as created_rows,
(select count(*) FROM @x and date(updated_at) = date(now())) as updated_rows

作为预备语句(https://dev.mysql.com/doc/refman/5.6/en/sql-syntax-prepared-statements.html)或proc(https://medium.com/@peter.lafferty/mysql-stored-procedures-101-6b4fe230967)的一部分,或仅合并即可获取多个表(请注意,您必须更改某些语法)。我不确定您需要如何运行它,因此不确定您到底需要什么,要获得什么样的性能,如果您只是要编写脚本并手动选择表,还是不确定试图在所有表等上运行它。

编辑:jxc的查询比我的查询好得多!

答案 2 :(得分:0)

这是您要找的东西吗?如果是这样,请确保在随后的UNION ALL查询中更改表名。

    SELECT 
    'accounts' AS TableName,
    SUM(DATE(updated_at) = DATE(NOW())) AS updated_rows,
    SUM(DATE(created_at) = DATE(NOW())) AS created_rows,
    DATE(NOW()) AS `Date`
    FROM
    accounts

    UNION ALL

    SELECT 
    'accounts2' AS TableName,
    SUM(DATE(updated_at) = DATE(NOW())) AS updated_rows,
    SUM(DATE(created_at) = DATE(NOW())) AS created_rows,
    DATE(NOW()) AS `Date`
    FROM
    accounts2

   and so forth....

EDIT (此查询与之前发布的jxc的查询相同)