开发者

need help prioritizing output with a SQL query

I'm trying to pull columns with a query where 'grad_year' is one of four years (4 OR statements), but I want entries of a specified year to appear first. This is the SQL I have. In this example, I want entries from 2011, 2012, 20开发者_运维百科13, and 2014. How do I get the 2012 entries, for example, to show up first? The rest of the order wouldn't matter. Thank you!

SELECT       user_meta.grad_year,
             school_data.school
FROM         user_meta
  LEFT JOIN  school_data
  ON         user_meta.school_id = school_data.id
WHERE        school_id = 2
  AND        user_id != 102
  AND       (user_meta.grad_year = 2011
    OR       user_meta.grad_year = 2012
    OR       user_meta.grad_year = 2013
    OR       user_meta.grad_year = 2014)
LIMIT        0, 15


Change the query to:

SELECT       user_meta.grad_year,
             school_data.school
FROM         user_meta
  LEFT JOIN  school_data
  ON         user_meta.school_id = school_data.id
WHERE        school_id = 2
  AND        user_id!=102
  AND       (user_meta.grad_year BETWEEN 2011 and 2014)
ORDER BY    (user_meta.grad_year = 2012) DESC
LIMIT        0, 15

This will show the 2012 items first and then all other items in accidental order.


this might help

ORDER BY 
 CASE 
  WHEN user_meta.grad_year = 2012 THEN 1 
  WHEN user_meta.grad_year = 2011 THEN 2 
  WHEN user_meta.grad_year = 2013 THEN 3 
  ELSE NULL 
 end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜