我有一个数据库,我在其中按地理位置列出事件(数据库中目前大约有 100000 个事件)。目前它处于一个很好的规范化模式中:表中的事件tevent
有一个外键fkvenue
,它指向表tvenue
中具有外键的场所fkcity
,依此类推到tregion
and tcountry
。
因此,查找具有最多事件的国家/地区的查询相当复杂,有不少于三个内部连接:
select r.fkcountry,count(distinct e.id) from tevent e
inner join tvenue v on e.fkvenue=v.id
inner join tcity cy on v.fkcity=cy.id
inner join tregion r on cy.fkregion=r.id
group by r.fkcountry order by count(distinct e.id) desc
我正在努力寻找加快速度的方法,我认为直接按国家/地区绘制事件地图可能会有所帮助。我创建了一个 map table teventcountry
,使用以下更简单的结果语法:
select ec.fkcountry,count(distinct e.id) from tevent e inner join teventcountry ec on ec.fkevent=e.id group by ec.fkcountry order by count(distinct e.id) desc
令我惊讶的是,这产生了完全相反的效果:新查询花费的时间几乎是旧的、更复杂的查询的五倍。
有人可以解释一下,或者指出一个很好的资源来帮助我了解多表查询的速度吗?或者甚至告诉我这类事情的首选模式?
(在有人问之前,我已经注意在运行之间进行“重置查询缓存”,以使计时结果有效,是的,我已经正确索引了所有内容!!!!)
谢谢
大卫