我正在尝试在此处优化我的查询,但不知何故,它仍然需要30秒以上才能执行。
它的外观如下:
SELECT v.cd, COUNT(vc.id) as count
FROM vc
INNER JOIN v ON v.uid = vc.vid
WHERE ct > 1393279200 AND pid="12" AND sid="10"
GROUP BY vc.vid;
我尝试了很多与JOIN的组合,但似乎根本不使用JOIN。也许建立子查询会更好吗?
期望的结果:
+--------------+--------------+
| cd | count |
+--------------+--------------+
| AE | 1 |
| AM | 1 |
| AU | 230 |
| BB | 1 |
| CA | 127 |
| CH | 1 |
| PR | 3 |
| SA | 1 |
| SE | 5 |
| SG | 12 |
| TH | 1 |
| US | 5829 |
| ZA | 3 |
+--------------+--------------+
36行(41.09秒)
由:
生成的所需结果SELECT V.cd, COUNT(VC.id) as count
FROM vc as VC, v V
WHERE ct > 1393279200 AND pid="12" AND sid="10" AND VC.vid = V.uid
GROUP BY V.cd;
答案 0 :(得分:0)
创建索引:
create index vcvid on vc (vid)
create unique index vuidcd on v (uid, cd)
注意:where语句中使用的列也应该在索引中,通常是第一个
运行analyze v; analyze vc; optimize v; optimize vc;
然后尝试此查询:
select v.cd, q.cnt
from
v use index (vuidcd)
inner join
(
select vc.vid, count(*) as cnt
from vc use index (vcvid)
group by vc.vid
) as q
on (v.uid = q.vid)
如果有问题 - 尝试使用explain extended
查询问题