简体   繁体   English

计算X天内在不同表中输入了多少行的最有效方法?

[英]Most efficient way to count how many rows have been entered in different tables within the X days?

Given several tables, what is the best way to take a poll of row counts in the tables with where clauses included? 给定几个表,采用where子句对表中的行计数进行轮询的最佳方法是什么? I'd like to do it at once so it can be inserted into a table with a daily record of row counts. 我想立即执行此操作,以便可以将其插入具有行计数的每日记录的表中。

tableA - count of all rows that fit condition 1, a specific column value X select count(*) from tableA where col1 = X tableA-满足条件1的所有行的计数,特定列值X从tableA中选择count(*),其中col1 = X

tableA - count of all rows that fit condition 2, a specific column value Y select count(*) from tableA where col2 = Y tableA-满足条件2的所有行的计数,特定列值Y从tableA中选择count(*),其中col2 = Y

These two are easily combined into: 这两个很容易组合成:

select
(select count(*) from tableA where col1 = X) as 'X count',
(select count(*) from tableA where col2 = Y) as 'Y count'

But now I'd like to add in: tableB - count of all rows that were created within the last specified interval 但现在我想添加:tableB-在最后指定间隔内创建的所有行的计数

select count(*) from tableB where dateCreated >= date_sub(curdate(), interval 1 day) where col3 = Z;

This gives me: 这给了我:

select
(select count(*) from tableA where col1 = X) as 'X count',
(select count(*) from tableA where col2 = Y) as 'Y count',
(select count(*) from tableB where dateCreated >= date_sub(curdate(), interval 1 day)) as 'Z count';

It seems to run very slowly though, is there a more efficient way of counting rows in this case? 但是,它运行似乎非常缓慢,在这种情况下,是否有更有效的计数行方法?

Your query looks fine, but you should index on those columns. 您的查询看起来不错,但是您应该在这些列上建立索引。 To do so, from the documentation : 为此,从文档中

CREATE INDEX idx_col1 ON tableA (col1);
CREATE INDEX idx_col2 ON tableA (col2);
CREATE INDEX idx_dateCreated on tableB (dateCreated);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM