SQL QUERY结果排列问题

时间:2012-06-19 18:56:28

标签: mysql sql

这是我的SQL查询:

select name,description 
from wp_widget_custom 
where name in ('hemel-hempstead','maidenhead',
  'guildford','bromley','east-london','hertfordshire','billericay','surrey')

我得到的结果是这种形式:

name            description
hemel-hempstead Loreum ipsim
east-london     Loreum ipsim
bromley         Loreum ipsim BROMLEY
billericay      Loreum ipsim
maidenhead      Loreum ipsim maidenhead
hertfordshire   Loreum ipsim HERTFORDSHIRE
guildford       loreum ipsum Guildford
surrey          loreum ipsum surrey

我希望结果按照在查询中传递的方式排列:

hemel-hempstead ,maidenhead',guildford,bromley,east-london......

感谢帮助,谢谢。

2 个答案:

答案 0 :(得分:6)

按字段排序:

select name, description
from wp_widget_custom
where name in ('hemel-hempstead','maidenhead','guildford','bromley','east-london','hertfordshire','billericay','surrey')
order by field(name, 'hemel-hempstead','maidenhead','guildford','bromley','east-london','hertfordshire','billericay','surrey')

答案 1 :(得分:1)

您可以使用过滤inner join而不是where ... in子句。这允许您指定一个订单,然后您可以在order by子句中引用该订单:

select  wc.name
,       wc.description 
from    wp_widget_custom wc
join    (
        select 1 as nr, 'hemel-hempstead' as name
        union all select 2, 'maidenhead'
        union all select 3, 'guildford'
        union all select 4, 'bromley'
        union all select 5, 'east-london'
        union all select 6, 'hertfordshire'
        union all select 7, 'billericay'
        union all select 8, 'surrey'
        ) as filter
on      filter.name = wc.name
order by
        filter.nr