2013-08-04 280 views
-4

重新寫我的查詢我有這個表:我需要一些幫助,在MySQL

ID   ITEM 
----------------- 
0001  345 
0001  345 
0001  120 
0002  567 
0002  034 
0002  567 
0003  567 
0004  533 
0004  008 
...... 

,爲了得到這樣的結果:

ID ITEM CNT 
1 008  0 
1 034  0 
1 120  1 
1 345  2 
1 533  0 
1 567  0 
2 008  0 
2 034  1 
... 

CNT是每個項目的的出現每個不同的ID

我運行此查詢:

select driver.id, driver.item, coalesce(count(t1.id), 0) 
from (select id.id, item.item 
     from (select distinct id from Table1) id cross join 
      (select distinct item from Table1) item 
    ) driver left outer join 
    Table1 t1 
    on driver.id = t1.id and driver.item = t1.item 
group by driver.id, driver.item; 

此查詢永遠服用,仍然一天後,還沒有完成.. 這是結果的說明:

Explain

idx_id和idx_code是編號和項目索引

燦你給我一些關於如何改進我的查詢的提示,這樣它可以運行得更快,並希望完成?謝謝

+1

結果並不能很好地解釋你想達到什麼。 – ep0

+0

[Count計數查詢花費的時間太長 - 已超過24小時]的可能重複(http://stackoverflow.com/questions/17996652/count-query-is-taking-too-long-over-24-hours-have - 已通過) – Chococroc

+0

CNT是每個不同ID的每個項目的出現次數 – user2578185

回答

3

我的建議是:分而治之。爲中間步驟創建臨時表,爲它們編制索引,然後使用它們來獲得最終結果。

具體做法是:

-- The deduplicated item list 
drop table if exists temp_items; 
create temporary table temp_items 
    select distinct item from Table1; 
alter table temp_items 
    add primary key (item); 

-- The deduplicated id list 
drop table if exists temp_ids; 
create temporary table temp_ids 
    select distinct id from Table1; 
alter table temp_ids 
    add primary key (id); 

-- The cross join 
drop table if exist temp_ids_items 
create temporary table temp_ids_items 
    select id, item 
    from temp_ids, temp_items; 
-- Important: Index the cross join 
alter table temp_ids_items 
    add index idx_id(id), 
    add index idx_item(item); -- Optionally: add unique index idx_dedup(id, item) 

現在你可以使用這個臨時表來獲得你所需要的:

select 
    a.id, a.item, coalesce(count(t1.id), 0) 
from 
    temp_ids_items as a 
    left join Table1 as t1 on (a.id = t1.id and a.item=t1.item) 
group by 
    a.id, a.item; 

我認爲你不需要coalesce()功能(如果算上null值,結果爲零),但這只是一個意見。

記住:臨時表僅對創建它們的連接可見,並且在連接關閉時它們被刪除。我認爲將所有上述過程放在存儲過程中可能很有用。

希望這有助於

+0

謝謝花時間回答我的問題..我會試試這個 – user2578185