How to improve this MySQL Query using join?

后端 未结 3 1104
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 18:53

I have got a simple query and it takes more than 14 seconds.

select 
     e.title, e.date, v.name, v.city, v.region, v.country

from seminar e force index for jo         


        
相关标签:
3条回答
  • 2021-01-21 19:36

    This would make the first part of the query faster:

    INDEX(city, region, country)
    
    0 讨论(0)
  • 2021-01-21 19:43

    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).

    0 讨论(0)
  • 2021-01-21 19:54

    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.

    0 讨论(0)
提交回复
热议问题