Skip to content
Advertisement

How to select matching results with other random results in mysql

I want to select all the matching results in a database table with also random results but with the matching results being at the top. With the way, I am doing now I am using two queries first one being the matching query, and if the count is zero I now select random results. I would like to do this with just one query.

Advertisement

Answer

You could attempt using a UNION ALL query as follows.

select product_name,price
  from marketing_table
 where price >=5000 /*user supplied filter*/
   and price <=10000 /*user supplied filter*/
union all
select m.product_name,m.price
  from marketing_table m
 where not exists (select *
                     from marketing_table m1
                    where m1.price >=5000 /*user supplied filter*/
                      and m1.price <=10000 /*user supplied filter*/
                   )
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement