简体   繁体   中英

MySql JOIN query with OR clause very slow

I have the following query:

SELECT a.id, b.from, b.to FROM a INNER JOIN b ON a.id = b.from OR a.id = b.to;

which is extremely slow.

If I remove the OR clause and run each query separately then the both queries execute under 1 second.

SELECT a.id, b.from, b.to FROM a INNER JOIN b ON a.id = b.from;
SELECT a.id, b.from, b.to FROM a INNER JOIN b ON a.id = b.to; 

How can I speed up the original query (set up indexes) or redesign the query itself?

What about using union?

SELECT a.id, b.from, b.to FROM a INNER JOIN b ON a.id=b.from
UNION
SELECT a.id, b.from, b.to FROM a INNER JOIN b ON a.id=b.to

How about the following instead. Just join to b twice:

SELECT a.id, b.from, b2.to 
FROM a 
INNER JOIN b ON a.id = b.from
INNER JOIN b b2 ON a.id = b2.to;

You may have to use LEFT JOIN instead if you don't always have a record for both cases.

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