I am trying to set up a sql query output with kind of an unusual sorting order. I have a site that features coupons that are rated by customers. I want to show all coupons that have a 50% or higher rating first, then those that have not yet been rated, followed lastly by anything with a low rating of less than 50%. The only way I can think to do it is with 3 queries each limiting the results by the requirements above. I'm not a seasoned SQL programmer so I'm not sure if this is even possible, but here is the basic logic of what I want to do: $goodquery=executeQuery(".... where tbl_coupon.success_rat>=50 group by tbl_coupon.id order by success_rat desc limit $start,$pagesize"); $newquery=executeQuery(".... where tbl_coupon.success_rat=0 group by tbl_coupon.id order by success_rat desc limit $start,$pagesize"); $badquery=executeQuery(".... where tbl_coupon.success_rat<50 group by tbl_coupon.id order by success_rat desc limit $start,$pagesize"); $query=$goodquery+$newquery+$badquery I realize this last line doesn't have the right syntax, this is just to represent what I want to do. Is this possible? If so, can anyone assist with the syntax? Thank you!!
Tyr using an IF in your select SELECT IF(tbl_coupon.success_rat>=50,1, IF(tbl_coupon.success_rat=0,2, IF(tbl_coupon.success_rat<50,3,4))) as 'myorder' ORDER by myorder; These are the basics, expand on that P.S. Your grouping by tbl_coupon.id but are not using an aggregate function on your tbl_coupon.success_rat, this is not good. You should min() , max(), avg() on every column that you select from your tbl_coupon table or loose your group by.
You can use subquery/subselect if your version of mysql support this feature, and union. Example SELECT a.WhateEver1 AS WE1, a.WhateEver2 AS WE2 FROM (SELECT WhateEver1, WhateEver2 FROM table WHERE WhatEver3 > 50 LIMIT 10) a UNION SELECT b.WhateEver1 AS WE1, b.WhateEver2 AS WE2 FROM (SELECT WhateEver1, WhateEver2 FROM table WHERE WhatEver3 = 0 LIMIT 10) b UNION SELECT c.WhateEver1 AS WE1, c.WhateEver2 AS WE2 FROM (SELECT WhateEver1, WhateEver2 FROM table WHERE WhatEver3 <= 50 LIMIT 10) c Code (markup):
Your third query is a superset of your second query: Q2...where tbl_coupon.success_rat=0 Q3...tbl_coupon.success_rat<50 Since 0<50, all the results of the 2nd query will also be in the results of the 3rd query.