简体   繁体   English

优化连接中的 MySQL“OR”查询

[英]Optimizing MySQL "OR" query in joins

I am facing some difficulty when using 'OR' queries with multi-table joins with MySql 5.7.在 MySql 5.7 中使用带有多表连接的“OR”查询时,我遇到了一些困难。

For example, let's say I want a list of Animals that are either currently at a location or are being shipped there.例如,假设我想要一个当前在某个位置或正在运送到那里的动物列表。

Select * from animals
left outer join animal_locations on animals.id = animal_locations.animal_id
left outer join animal_shipments on animals.id = animal_shipments.animal_id
where animal_locations.location_id = 5 OR animal_shipments.location_id = 5

The queries are very fast when using "AND" as well as using individual columns without any operator.使用“AND”以及使用没有任何运算符的单个列时,查询速度非常快。 But when "OR" queries are used, there is a big performance hit, the right indexes are not being hit.但是当使用“OR”查询时,性能会受到很大影响,没有命中正确的索引。

Any way I can achieve this without splitting it up into multiple queries?有什么办法可以在不将其拆分为多个查询的情况下实现这一目标?

SELECT * 
FROM animals
LEFT OUTER JOIN animal_locations ON animals.id = animal_locations.animal_id
                                AND animal_locations.location_id = 5
LEFT OUTER JOIN animal_shipments ON animals.id = animal_shipments.animal_id
                                AND animal_shipments.location_id = 5
WHERE COALESCE(animal_locations.animal_id, animal_shipments.animal_id) IS NOT NULL

The logic - previously the rows in slave tables with location_id = 5 are filtered, and then filtered rows are joined to main table.逻辑 - 以前从表中location_id = 5被过滤,然后过滤后的行连接到主表。

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

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