Calculating difference with mysql

Hello,

I want to run a query to fetch 10 rows from database with the ‘category_id’ parameter set, and fall back if there are not 10 rows from the mentioned category to fetch the missing rows from the same table without category_id.

How can you calculate a difference with php?

Right now I call this query:

(SELECT asin FROM products $where ORDER BY $order_by LIMIT 10)
	    UNION
	    (SELECT asin FROM products WHERE site_id = $site_id ORDER BY $order_by LIMIT 10)

And then use splice_array in php to get the first 10.

Which would be more elegant way to do this with mysql?

Thanks for help

There’s nothing wrong with this way, IMO :slight_smile:
I don’t know if it would be possible to have MySQL establish how many rows are extracted from the category, and how many rows must be added from the entire table, but even if it is, I’m sure it would be much more complicated than coding that piece of logic in PHP (like you said, all you need there is array_splice).