简体   繁体   中英

mySQL Query Optimization (LEFT JOIN & SUBQUERY)

SELECT table1.waypoint,table1.latitude,
       table1.longitude,table1.airway
FROM 
  airways table1
JOIN 
   (SELECT * FROM airways
    WHERE waypoint='KORED') AS table2
  ON table1.airway = table2.airway 
WHERE table1.sequence=table2.sequence+1 
   OR table1.sequence=table2.sequence-1

Hello,

I'm trying to optimize the above query. The query time is pretty high at the moment (around 0.9s). I'm only using one table (~100k entries), JOINING it with itself. The IN syntax doesn't work in my Synology MYSQL 5.1. (Somehow makes it crash using SELECT s1 FROM t1 WHERE s1 IN (SELECT s1 FROM t2); The query time is around 0.2s without using the WHERE part of it. I've Indexed the table on sequence and waypoint .

Thank you!

Not sure if this will help as much as my suggestion of actually adding these fields to the table itself and indexing on them, but you might try just moving the math out of the where and into the select:

SELECT table1.waypoint,table1.latitude,
       table1.longitude,table1.airway
FROM 
  airways table1
JOIN 
   (SELECT *,sequence + 1 as sequence_inc, sequence - 1 as sequence_dec FROM airways
    WHERE waypoint='KORED') AS table2
  ON table1.airway = table2.airway 
WHERE table1.sequence=table2.sequence_inc
   OR table1.sequence=table2.sequence_dec

EDIT Ok, so that doesn't help, but based on your explain I think the real problem is a lack of index on the airway field of the airways table that you are using to join. Add that index and see if that improves your performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM