Given several tables, what is the best way to take a poll of row counts in the tables with where clauses included? 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 - count of all rows that fit condition 2, a specific column value Y select count(*) from tableA where 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
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.