Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用“或”时优化MySQL查询_Mysql - Fatal编程技术网

使用“或”时优化MySQL查询

使用“或”时优化MySQL查询,mysql,Mysql,这两个表包含超过100万条记录 此查询需要15秒运行,并返回1条正确记录: select orders.* from orders left join orders_details on orders.orderID=orders_details.orderID where orders_details.trackingRef='GYD41624' or orders.orderID = ( select distinct orderID f

这两个表包含超过100万条记录

此查询需要15秒运行,并返回1条正确记录:

    select orders.*
        from orders
    left join orders_details on orders.orderID=orders_details.orderID
        where 
orders_details.trackingRef='GYD41624' 
or orders.orderID = (
select distinct  orderID from orders_rebookings
 where trackingRef='GYD41624'
)   
    group by orders.orderID
然而,如果我分别使用每个where条件运行查询,则每个条件都非常快:

这需要0.0015秒才能找到1个匹配项:

select orders.*
    from orders
left join orders_details on orders.orderID=orders_details.orderID
    where orders.orderID = (select distinct orderID from orders_rebookings where trackingRef='GYD41624')    
group by orders.orderID
这几乎不需要时间,也找不到匹配项这是正确的:

select orders.*
    from orders
left join orders_details on orders.orderID=orders_details.orderID
    where orders_details.trackingRef='GYD41624'     
group by orders.orderID
因此,如果我有两个非常快速的查询,如何使第一个查询包含或几乎一样快?

您可以使用union或union all组合它们:

select o.*
from orders o left join
    orders_details od
    on o.orderID = od.orderID
where o.orderID = (select distinct orderID from orders_rebookings where trackingRef = 'GYD41624')    
group by o.orderID
union
select o.*
from orders o left join
     orders_details od
     on o.orderID = od.orderID
where od.trackingRef = 'GYD41624'     
group by o.orderID;
联合的效率稍低,因为它会删除重复项

您的查询也很危险,因为它具有=select。。如果子查询返回多行,您将得到一个错误

我想知道这种形式是否会更好:

select o.*
from orders o
where exists (select 1 from orders_details where o.orderID = od.orderID and od.trackingRef = 'GYD41624') or
      exists (select 1 from orders_rebookings orr where o.orderID = orr.orderID and orr.trackingRef = 'GYD41624')       

您可能需要相应的索引orders\u detailsorderId,TrackingRef和orders\u rebookingsorderId,TrackingRef.

-将子查询中的distinct from替换为一个组byHi。好主意,我没考虑过这个。我这里的问题是,我遇到的问题实际上包含在一个更大的查询中。我只是把这一点孤立出来,让例子更清楚。我可能能够将union概念应用到大型查询中,但我希望得到一些非常简单的东西:-