Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL QUERY Result arrangement issue

Tags:

sql

mysql

This is my SQL query:

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

The result I am getting is in this form:

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

I want the result to be arranged the way it was passed in the query:

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

Help is appreciated, thanks.

like image 403
Shoaib Ahmed Avatar asked Jun 19 '12 18:06

Shoaib Ahmed


2 Answers

order by field:

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')
like image 148
Andrew Kuklewicz Avatar answered Oct 08 '22 17:10

Andrew Kuklewicz


You could use a filtering inner join instead of an where ... in clause. That allows you to specify an order, which you can then reference in the order by clause:

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
like image 33
Andomar Avatar answered Oct 08 '22 17:10

Andomar