繁体   English   中英

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

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

给定几个表,采用where子句对表中的行计数进行轮询的最佳方法是什么? 我想立即执行此操作,以便可以将其插入具有行计数的每日记录的表中。

tableA-满足条件1的所有行的计数,特定列值X从tableA中选择count(*),其中col1 = X

tableA-满足条件2的所有行的计数,特定列值Y从tableA中选择count(*),其中col2 = Y

这两个很容易组合成:

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

但现在我想添加:tableB-在最后指定间隔内创建的所有行的计数

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

这给了我:

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';

但是,它运行似乎非常缓慢,在这种情况下,是否有更有效的计数行方法?

您的查询看起来不错,但是您应该在这些列上建立索引。 为此,从文档中

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