Skip to main content
1 of 4

Get a list of orders by excluding the recents one in the same category?

I have a table of the following structure (simplified):

Table orders

  • id
  • created
  • name
  • executed
  • category_id

I need a list of n orders from distinct categories (if n is 5, I should have at most 5 different categories, and never two same categories). I successfully done this one using the following request :

 SELECT name FROM orders WHERE executed IS NULL GROUP BY category_id LIMIT 5;

But I'd need to exclude the categories that has already been processed less than an hour ago.

For that, I was able to do the following query :

SELECT name, category_id FROM orders WHERE executed IS NULL AND category_id NOT IN (SELECT category_id FROM orders WHERE executed > (UTC_TIMESTAMP() - INTERVAL 60 MINUTE) GROUP BY category_id) GROUP BY category_id LIMIT 5;

But I was wondering if there was a faster way to get the results.

I've made an SQLFiddle to show my example, but I find it quite slow and I was not able to get a successful result from them.