2013-07-25 11 views
0

給出幾個表格,在where子句包括的表格中對行計數進行輪詢的最佳方式是什麼?我希望立即做到這一點,以便將其插入到具有行計數每日記錄的表格中。計算X天內在不同表格中輸入了多少行的最有效方法?

TABLEA - 從表A適合條件1,一個特定的列值X SELECT COUNT(*)的所有行的計數,其中COL1 = X

TABLEA - 適合條件2,一特定列中的所有行的計數從表A值Y SELECT 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; 

此範圍內創建的L行給我:

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

它似乎運行,雖然速度很慢,有沒有在這種情況下計算行的更有效的方法?

+0

如果表使用InnoDB引擎,然後計數將在一般慢,因爲每一行都必須被訪問,以確定它是否是當前的交易可見。 (對於這樣的查詢,MyISAM會稍微好一些,因爲它只能訪問匹配的索引。) – cdhowie

+1

在'TableA(col1)和'TableB(dateCreated)'上創建索引以加快查詢速度。 –

回答

0

您的查詢看起來不錯,但您應該在這些列上編制索引。要做到這一點,從the documentation

CREATE INDEX idx_col1 ON tableA (col1); 
CREATE INDEX idx_col2 ON tableA (col2); 
CREATE INDEX idx_dateCreated on tableB (dateCreated); 
相關問題