How to improve this MySQL Query using join?

故事扮演 提交于 2019-12-02 02:23:57

You have left join venues, but you have conditions in the where clause on the joined venues row, so only joined rows will be returned. However, that's a side issue - read on for why you don't need a join at all.

Next, if the city is vancouver, there's no need to also test for country or state.

Finally, if you're trying to find "how many future events are in Vancouver", you don't need a join, as the venue id is a constant!

Try this:

select count(*) as event_count
from events
where venueid = (select id from venues where city = 'vancouver')
and startdate > curdate() 
and te_id != 0

Mysql will use the index on venueid without you having to use a hint. If it doesn't, execute this:

analyze events

which will update the statistics of the data distribution in the indexed columns. Note that if a lot of your events are in Vancouver, it's more efficient to not use an index (as most of the rows will have to be accessed anyway).

This would make the first part of the query faster:

INDEX(city, region, country)

I went another way since it seems that MySQL can't handle joins effectively:

  • Created one big new table with all the columns I need from the join
  • So the seminars and events are in one table now
  • added indexes

Now the query is fast. Don't know why...

From 25 seconds, we are down to .08 seconds

That's how I wanted it.

If anybody still knows why, you are more than welcome to provide an answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!