I have two tables:
user_favourites -> id, user_id, product_id
product -> id, title, bought
I need to display 9 results -> user favourites plus other products if user has less than 9 favourites.
So on my page there should be 9 products displayed. If user has selected 9 favourite product then I will display those 9 favourites, if he has selected less than 9 ( lest say 5 ), then I have to display 5 of his favourites plus 4 highest rated products from the system.
To get user favourites I have this query :
select product_id from user_favourites where user_id = $userId
To get highest rated products I have this query:
select id, title, count(bought) from product group by id limit 9
So since I want to display first favourite products + most popular ones if user has not selected 9, can I somehow merge these two queries into one to get the desired result ? Please not one problem here, I need to remove duplicates. If product with id of 999 is chosen by user but he is also among the most popular ones, I need to display it only once. Also I need to get max of 9 results.
What is the most elegant way of doing this using php and mysql ?
to expand slightly on dirluca's fine work
-- ignore the ordering column, naturally, when plopping in gui