赶知识网

如何让ORDER BY 按指定的顺序排序?

2012-10-12 / 17958次点击 php/mysql/apache
表里有个列叫Type,是商品类别,就3种情况:S,A,B。现在我需要按照SAB的顺序排序,那位大侠能帮帮忙啊,
SELECT   *
FROM   tbl_test
ORDER   BY   " ? 这里应该咋写? "
两个表联合查肯定没问题,现在就是想如果单独用这个表的话。咋弄。多谢啦!!!!

答案1:使用union all
select   *   from   table   where   type= 'S '   union   all
select   *   from   table   where   type= 'A '   union   all
select   *   from   table   where   type= 'B '

答案2:使用case语句
order   by   case   type   when   's '   then   1
    when   'a '   then   2   when  'b '   then   3   else   4   end

答案3:使用charindex函数,仅适用于MS SQL Server
order   by   charindex(type+ ', ', 'S,A,B, ')

答案4:Php + MySQL按照指定顺序排列问题order by
在做程序的时候会用到按照指定的顺序输出数据库内容:
在mysql语句中这样写: select * from table where .... order by field(字段名,'2','8','5','1'),这里的  2 8 5 1 是按照自己的要求排序的,很简单的搞定,这样在foreach中循环就不用做任何其他操作了,直接一个循环搞定。

有用 2 没用 1

Top10

沪ICP备09053415号 © 赶知识网