2013-08-04 170 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