[英]What is the most efficient way to organise these tables + rows? - MySQL
[英]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.