title: Laravel orWhere() / MySQL or query taking a long time
body: <p>I'm using Laravel 4.2 and my application is used for tracking inventory across multiple locations.</p>
  
  <p>The database is set up with an <code>inventory_items</code> table, <code>inventory_locations</code> table and a pivot table between them <code>inventory_items_inventory_location</code>, which contains the quantity values whilst referencing both the inventory item and location the record belongs to.</p>
  
  <p>My query is to find inventory items that have any location quantity value more than or equal to 0. In Laravel I'm using a subquery and orWhere like so:</p>
  
  <pre><code>InventoryItem::whereHas('inventoryLocations', function($q) {
    $q-&gt;where('reserved', '&gt;=', 0)
       -&gt;orWhere('available', '&gt;=', 0) # slow
       -&gt;orWhere('inbound', '&gt;=', 0) # slow
       -&gt;orWhere('total', '&gt;=', 0); # slow
  })-&gt;toSql();
  </code></pre>
  
  <p>Which gives the following SQL:</p>
  
  <pre><code>select * from `inventory_items`
  where `inventory_items`.`deleted_at` is null
  and (
    select count(*) from `inventory_locations`
    inner join `inventory_item_inventory_location`
    on `inventory_locations`.`id` = `inventory_item_inventory_location`.`inventory_location_id` 
    where `inventory_item_inventory_location`.`inventory_item_id` = `inventory_items`.`id`
    and `reserved` &gt;= ?
    or `available` &gt;= ? # slow
    or `inbound` &gt;= ? # slow
    or `total` &gt;= ? # slow
  ) &gt;= 1
  </code></pre>
  
  <p>The problem is that with the <code>or</code> statements (marked in the code by <code>#slow</code>) the query time is up to 1s directly with Sequel Pro, more than 5s through my Laravel app (or through artisan tinker). Without these 'or' checks (i.e. just checking for one quantity type e.g. 'reserved') the query is &lt;100ms on Sequel Pro and similar on the app/tinker.</p>
  
  <p>I'm not sure why adding these extra 'or' checks adds so much time to the query. Any ideas how to make a more performant query?</p>