简体   繁体   English

使用OR子句的MySQL JOIN查询非常慢

[英]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. 如果删除OR子句并分别运行每个查询,则两个查询将在1秒内执行。

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: 只需加入b两次:

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. 如果您并非总是有两种情况的记录,则可能必须使用LEFT JOIN。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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